I am trying to tag links in a string by adding a redirect. The data comes out of MySQL database in a string format and looks something like this:
$string = "<p><a href='http://twitter.com'>Follow on Twitter</a> and please friend on <a href='http://facebook.com'>Friend on Facebook</a></p>";
I am using the function strpos together with the needle "http" to get the location of all the links in the string and store them in an array called positions. The array gets filled with the character at which the link starts and looks like this:
Array
(
[0] => 12
[1] => 100
)
I then loop through the positions array and use substr_replace to add the redirect link before the http. However, this only works for one link and if I have multiple links in the string it gets overwritten. Anyone have any clever solution to this?
Here is my code:
function stringInsert($str,$pos,$insertstr)
{
if (!is_array($pos))
$pos=array($pos);
$offset=-1;
foreach($pos as $p)
{
$offset++;
$str = substr($str, 0, $p+$offset) . $insertstr . substr($str, $p+$offset);
}
return $str;
}
$string = "<p><a href='http://twitter.com'>Follow on Twitter</a> and please friend on <a href='http://facebook.com'>Friend on Facebook</a></p>";
$needle = "http";
$lastPos = 0;
$positions = array();
while (($lastPos = strpos($string, $needle, $lastPos))!== false) {
$positions[] = $lastPos;
$lastPos = $lastPos + strlen($needle);
}
$str_to_insert = "http://redirect.com?link=";
foreach ($positions as $value) {
$finalstring = substr_replace($string, $str_to_insert, $value, 0);
}
The final outcome should look like:
$string = "<p><a href='http://redirect.com?link=http://twitter.com'>Follow on Twitter</a> and please friend on <a href='http://redirect.com?link=http://facebook.com'>Friend on Facebook</a></p>";
I think a more comfortable solution could be using str_replace (http://php.net/manual/en/function.str-replace.php)
do something like this:
$string = str_replace(
['http://','https://'],
['http://redirect.com?link=http://', 'http://redirect.com?link=https://'],
$sourceString
);