user2865417 user2865417 - 5 months ago 9
PHP Question

how to get the position of a string in a long text which is inside in a href attribute using php

I have an html text like :

$html = "<img src='http://testlink.com/something' />
<a href='http://testlink.com'></a>
<a href='http://testlink.com/something/index.php'></a>";


So when I try to replace the string "http://testlink.com" from the $html with "http://example.com" I need a result like :

<img src='http://testlink.com/something' />
<a href='http://example.com'></a>
<a href='http://testlink.com/something/index.php'></a>


which means the replace only work with the string which is inside in a href attribute and that href attribute should only contain the specified value which I want to replace .

Answer

I would use a DOM Parser such as PHP Simple HTML DOM Parser to search for a link with http://testlink.com as href and then replace it with http://example.com.

include 'simple_html_dom.php';

$html = "<img src='http://testlink.com/something' />    
<a href='http://testlink.com'></a>
<a href='http://testlink.com/something/index.php'></a>";

$dom = str_get_html($html);
$dom->find('a[href="http://testlink.com"]', 0)->href = 'http://example.com';

echo $dom;

Output:

<img src='http://testlink.com/something' />      <a href='http://example.com'></a>  <a href='http://testlink.com/something/index.php'></a>
Comments