获取标题变量PHP中的图像属性

时间:2014-03-26 07:40:13

标签: php html arrays function dom

如何从图片代码中获取title

$img = '<img src="./img/icons/locale_en.gif" title="English">';

我需要输出英语

3 个答案:

答案 0 :(得分:2)

使用DOMDocument类。

echo $dom->getElementsByTagName('img')->item(0)->getAttribute('title');

Demo

答案 1 :(得分:1)

使用正则表达式:

$img = '<img src="./img/icons/locale_en.gif" title="English">';
preg_match('~title[ ]*=[ ]*["\'](.*?)["\']~is',$img,$match);
echo "title is ".$match[1];

这也是可能的:

$img = '<img src="./img/icons/locale_en.gif" title="English"><img src="./img/icons/locale_nl.gif" title="Dutch">';
preg_match_all('~title[ ]*=[ ]*["\'](.*?)["\']~is',$img,$match);
foreach($match as $key=>$val)
{
  echo 'title is '.$match[1][$key]."<br />\n";
}

答案 2 :(得分:0)

您可以解析字符串以查找title=",然后解析结束"并获取其间的子字符串。像这样的东西会起作用:

$title = explode(" title=\"", $img);
$title = $title[1]; // get the part after title="
$title = explode("\"", $title);
$title = $title[0]; // get the part before "