2010-02-05 126 views
2

我从一个JSON提要得到这个:PHP字符串添加标签(修改)

<img src = "http://produits-lemieux.com/produits/bainmoussant_hg.jpg" ></img> 

我需要注入alt=""到字符串

做,在PHP的最佳方法是什么?

回答

3
string = '<img src = "http://produits-lemieux.com/produits/bainmoussant_hg.jpg" ></img>'; 
str_replace('></img>', 'alt=""></img>', $string); 

不知道为什么你有</img>时,你可以这样做:alt="" />

+0

ALT应该是IN IMG标记,而不是在.. – menardmam 2010-02-05 15:48:37

1

操纵与DOM functions的HTML DOM?

$doc = new DOMDocument(); 
    $doc->loadHTML("<html><body>Test<br></body></html>"); 
    $params = $doc->getElementsByTagName('img'); // Find Sections 

    foreach($params as $param) 
    { 
    $attribute = $doc->createAttribute('alt'); 
    $param->appendChild($root_attr1); 

    $attributeText = $doc->createTextNode('This is the ALT attribute'); 
    $attribute->appendChild($root_text); 
    } 

    $doc->saveHTML(); 

您可以使用createAttribute函数添加属性。

+0

似乎过度杀伤。 – 2010-02-05 15:34:46

+0

这可能是矫枉过正,但对学习很有帮助。 – 2010-02-05 16:34:22