dflow Posted May 16, 2011 Share Posted May 16, 2011 how should i approach this with preg_match? i have a text: "big red apple" now i want the script to create a href for each keyword apple and link to http://apple.com examples appreciated Quote Link to comment Share on other sites More sharing options...
dragon_sa Posted May 16, 2011 Share Posted May 16, 2011 <?php $text="big red apple at microsoft"; $change=array("apple", "microsoft"); $with=array("<a href='http://www.apple.com'>apple</a>", "<a href='http://www.microsft.com'>microsoft</a>"); $changed=str_replace($change, $with, $text); echo "Original text was $text <br/>"; echo "New text is $changed"; ?> Quote Link to comment Share on other sites More sharing options...
dflow Posted May 16, 2011 Author Share Posted May 16, 2011 <?php $text="big red apple at microsoft"; $change=array("apple", "microsoft"); $with=array("<a href='http://www.apple.com'>apple</a>", "<a href='http://www.microsft.com'>microsoft</a>"); $changed=str_replace($change, $with, $text); echo "Original text was $text <br/>"; echo "New text is $changed"; ?> mucho grasias!!! Quote Link to comment Share on other sites More sharing options...
PFMaBiSmAd Posted May 16, 2011 Share Posted May 16, 2011 If you use preg_replace, you can do a case-insensitive search and you can get the code to form the links for you - <?php $search = "apple"; // use the | to separate multiple keywords - "red|apple" $string = "big red apple"; $string = preg_replace("/($search)/i",'<a href="http://\1.com">\1</a>',$string); echo $string; ?> Quote Link to comment Share on other sites More sharing options...
dragon_sa Posted May 16, 2011 Share Posted May 16, 2011 does that also create multiple different links aswell? eg apple.com and red.com if both keywords were entered or is the syntax different Quote Link to comment Share on other sites More sharing options...
PFMaBiSmAd Posted May 16, 2011 Share Posted May 16, 2011 <?php $search = "proposition|seven|nation|liberty|continent"; // use "red|apple" to match multiple keywords $string = "Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal."; $string = preg_replace("/($search)/i",'<a href="http://\1.com">\1</a>',$string); echo $string; ?> Quote Link to comment Share on other sites More sharing options...
dragon_sa Posted May 16, 2011 Share Posted May 16, 2011 very nifty Quote Link to comment 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.