young_coder Posted February 21, 2010 Share Posted February 21, 2010 Hey guys! I'm working on this little script but I’m novice with PHP and I can not find out solution for this alone, so please will somebody help me. Link looks like this: <a href="word1-word2-word3">word1-word2-word3</a> And I need to be without hyphens like this in part highlighted with red <a href="word1-word2-word3">word1 word2 word3</a> Here is my script <? function makeLinksFromWords($text) { $text = html_entity_decode($text); $text = " ".$text; $text = preg_replace('/ link:(\S+)/', ' <a href="$1">$1</a>', $text); return $text; } // Live Example echo makeLinksFromWords("This is a example for link link:word1-word2-word3"); ?> Would appreciate some help with this one and thank you advance Cheers! Quote Link to comment https://forums.phpfreaks.com/topic/192806-small-trouble-with-preg_replace/ Share on other sites More sharing options...
salathe Posted February 21, 2010 Share Posted February 21, 2010 To manipulate the value in the replacement (i.e. what becomes the <a> tag) you can use a callback like: function makeLinkFromMatch($match) { $link = $match[1]; $text = str_replace('-', ' ', $match[1]); return sprintf(' <a href="%s">%s</a>', $link, $text); } You would then need to change preg_replace to instead use preg_replace_callback: $text = preg_replace_callback('/ link:(\S+)/', 'makeLinkFromMatch', $text); If you haven't use preg_replace_callback before, it may be a little confusing so do check out the documentation for it and ask here if you're unsure. Quote Link to comment https://forums.phpfreaks.com/topic/192806-small-trouble-with-preg_replace/#findComment-1015632 Share on other sites More sharing options...
young_coder Posted February 21, 2010 Author Share Posted February 21, 2010 This is Ok $text = preg_replace('/ link:(\S+)/e', '" <a href="."\\1".">".str_replace("-"," ","\\1")."</a>"', $text); Quote Link to comment https://forums.phpfreaks.com/topic/192806-small-trouble-with-preg_replace/#findComment-1015643 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.