2014-03-26 27 views
-2

如何从图像标签获取title获取标题变量中的图像属性PHP

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

我需要得到英语作为输出。

+1

为了解析HTML容易,您可以使用http://simplehtmldom.sourceforge .net/ – Scipius2012

+0

你是如何得到这个字符串的?它不是更大一块HTML的一部分吗? –

回答

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"; 
} 
0

您可以解析字符串,找到title=",然后关闭"并获取其中的子字符串。像这样的东西可以工作:

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

使用DOMDocument类。

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

Demo