brunelle25 Posted November 18, 2014 Share Posted November 18, 2014 What I'm trying to do is replace message_tags to links and web addresses to links in facebook json data, the problem is I need to do these in 2 steps, first do the message tags then then web addresses. The message_tags need to be done first because they rely on offset and length of the message to do the replace. To code to first replace the message_tags is // convert message tags to links if($post->message_tags) { usort($post->message_tags, 'mySort'); foreach($post->message_tags as $message_tag) { foreach($message_tag as $link) { $post_text = substr_replace($post_text,"<a href=\"https://www.facebook.com/".$link->id."\" target=\"_blank\">".$link->name."</a>",$link->offset,$link->length); } } } The second part is to convert any web address (http://example.com) to a link (<a href ="http://example.com" title="http://example.com" target="_blank">http://example.com</a>) // check if any entites exist and if so, replace them with hyperlinked versions $post_text = preg_replace("/((http:\/\/|https:\/\/)[^ )]+)/e", "'<a href=\"$1\" title=\"$1\" target=\"_blank\">'. ((strlen('$1')>=250 ? substr('$1',0,250).'...':'$1')).'</a>'", $post_text); So now to the problem, the second part now rewrites the first part and completely destroys the link because it just looks for http: and https: so in my preg_replace I need a way to not include anything that has already been converted, so not include anything that already has href="http Link to comment https://forums.phpfreaks.com/topic/292529-looking-for-some-help-to-not-include-something-in-preg_replace/ Share on other sites More sharing options...
Ch0cu3r Posted November 18, 2014 Share Posted November 18, 2014 if the message tags does not contain http:// links then replace urls in $post_text before replacing the message tags. Also you should not use e pattern modifier for you replacement string. This could allow a hacker to run malicious code. It is is better to use preg_replace_callback. Your regex converted below // for each match this function is called. It will wrap the url in HTML anchor tags function url_to_link($matches) { $url = $matches[0]; $link = "<a href=\"$url\" title=\"$url\" target=\"_blank\">"; $link .= strlen($url) >=250 ? substr($url, 0, 250) . '...' : $url; $link .= '</a>'; // return the HTML for the link return $link; } $post_text = preg_replace_callback("/(https?:\/\/[^\s]+)/", 'url_to_link', $post_text); Link to comment https://forums.phpfreaks.com/topic/292529-looking-for-some-help-to-not-include-something-in-preg_replace/#findComment-1496882 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.