【问题标题】:Dynamically add img alt tags within HTML markup in PHP在 PHP 中的 HTML 标记中动态添加 img alt 标签
【发布时间】:2015-03-10 10:25:16
【问题描述】:

我有 HTML,我在其中使用 HTML 回显到页面上。 HTML 标记包含图像,其中一些没有 alt 标签。图像标记没有设置格式 - 因为它是从 WordPress 导出的,格式混乱。

我需要能够解析 HTML,找到没有 alt 标记或空 alt 标记的图像并用文本填充。

【问题讨论】:

  • 请一些代码。还有更多信息:您是否使用 PHP 输出 HTML 文件的内容?是 php 生成的“img”标签还是静态 html?
  • @Federico 正如我在帖子中所说,我将 HTML 回显到页面上,HTML 中有“img”标签 - 它们都不是特定格式。
  • 只有在您向我们展示您拥有的代码以及它在哪里不起作用时,我们才能为您提供帮助。如果您完全不知道如何解决此问题,我建议您采用类似于 this 的方法,在该方法中检查 alt 属性是否存在。

标签: php html alt


【解决方案1】:

试试这个:

它试图找到没有 alt 属性或宽度为空的 alt=""img

而不是将图像替换为 alt=" my_text "

$content = '
replace alt <img src="aaaa" alt="" />
replace alt <img src="bbbb" alt=" " />
replace alt <img src="cccc" />
do nothing  <img src="dddd" alt="xxxxxxx" />
do nothing  <img src="eeee" alt="yyyyy" />
error:      <img src="ffff" alt="" alt="  " />
';

function replace_alt($html_content, $alt_text='')
{   $count = preg_match_all('/<img[^>]+>/i', $html_content, $images);
    if($count>0)
    {   $o = $html_content;
        $t = 'alt="'.$alt_text.'" ';
        foreach($images[0] as $img)
        {   $is_alt = preg_match_all('/ alt="([^"]*)"/i', $img, $alt);
            if($is_alt==0)
            {   $new_img = str_replace('<img ', '<img '.$t , $img);
                $o = str_replace($img, $new_img, $o);
            }
            elseif($is_alt==1)
            {   $text = trim($alt[1][0]);
                if(empty($text))
                {   $new_img = str_replace(trim($alt[0][0]), $t, $img);
                    $o = str_replace($img, $new_img, $o);
                }
            }
        }
    }
    return $o;
}

echo replace_alt($content, 'TEST');

$content 应该是您的完整 HTML 页面....

【讨论】:

  • 我认为这会起作用 - 我如何让它搜索:alt="", alt="" 并且根本没有 alt?
  • 我已经更新了它现在它还可以查找和替换空的alt
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
相关资源
最近更新 更多