note 119793 added to function.str-replace
| From: | viundan at gmail dot com | Date: | Fri, 26 Aug 2016 16:08:24 +0000 |
| Subject: | note 119793 added to function.str-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-206400@lists.php.net to get a copy of this message | ||
Decision to avoid problem "it might replace a previously inserted value when doing multiple
replacements. See also the examples in this document."
$urls - array of urls i want to replace with tag <a> and urls could be similar
http://abc.com/parameter/
http://abc.com/
// at first sort by length to have longest firstly
usort($urls,'sortByLen');
$replaces=[];
// replace all urls with unique
foreach($urls as $url){
$replace = '__REPLACE' . uniqid() . '__';
$text = str_replace($url,$replace, $text);
$replaces[$replace] = '<a href="' . $url . '">' . $url .
'</a>';
}
foreach($replaces as $key => $replace){
$text = str_replace($key,$replace, $text);
}
--------------
function sortByLen($a,$b){
return strlen($b)-strlen($a);
}
Hope it will help others like me
----
Server IP: 72.52.91.14
Probable Submitter: 178.150.175.132
----
Manual Page -- http://php.net/manual/en/function.str-replace.php
Edit -- https://master.php.net/note/edit/119793
Del: integrated -- https://master.php.net/note/delete/119793/integrated
Del: useless -- https://master.php.net/note/delete/119793/useless
Del: bad code -- https://master.php.net/note/delete/119793/bad+code
Del: spam -- https://master.php.net/note/delete/119793/spam
Del: non-english -- https://master.php.net/note/delete/119793/non-english
Del: in docs -- https://master.php.net/note/delete/119793/in+docs
Del: other reasons-- https://master.php.net/note/delete/119793
Reject -- https://master.php.net/note/reject/119793
Search -- https://master.php.net/manage/user-notes.php