Php search for specific links and append the url after them -
i have string following patterns
$mystring="bla <a href="website.com"></a>";
with few more links , other html tags.
i want use php function to:
search href tags contain specific word. in case, word
website.com
.append text link same url every occurrence.
example:
<a href="website.com?bla"></a>
should become to:
<a href="website.com?bla"></a><br><a href="website.com?bla">new link here</a>
and same goes rest links.
how go doing this?
first of all, should iterate around occurrences, using strpos
method, using lastpos
offset. insert string/new link, after finding closing
$needle = "website.com?"; // word find $endlink = "</a>" $lastpos = 0; $str_to_insert = "<br><a href=\"website.com?bla\">new link here</a>" // text append while (($lastpos = strpos($mystring, $needle, $lastpos))!== false) { //position after finding string is: occurrence + string length $lastpos = $lastpos + strlen($needle); //finding end of link (to append there) $writepos = strpos($mystring, $endlink, $lastpos); //appending string , updating $mystring $mystring = substr_replace($mystring, $str_to_insert, $writepos, strlen($endlink); //add appended string lastpos, avoid searching $lastpos = $writepos + strlen($str_to_insert) }
edit
making $str_to_insert
dynamic:
while (($lastpos = strpos($mystring, $needle, $lastpos))!== false) { $str_to_insert = substr($mystring, $lastpos, len($needle) //position after finding string is: occurrence + string length $lastpos = $lastpos + strlen($needle); // ... rest keeps same }
Comments
Post a Comment