1

I am being "thick this morning" so please excuse this simple question - I have an array of keywords e.g. array('keyword1','keyword2'....) and I have a string of text - (bit like a blog content in length i.e. not just a few words but may be 200-800 words) what is the best way to search the string for the keywords and replace them with an href link. So in the text 'keyword 1' (as plain text) will become <a href='apage'>keyword1</a> and so on.

See said was being thick this am.

Thanks in adavance.

Russell Parrott
  • 873
  • 7
  • 19
  • 38

2 Answers2

3

Typical preg_replace case:

$text = "There is some text keyword1 and lorem ipsum keyword2.";
$keywords = array('keyword1', 'keyword2');

$regex = '/('.implode('|', $keywords).')/i';

// You might want to make the replacement string more dependent on the
// keyword matched, but you 'll have to tell us more about it
$output = preg_replace($regex, '<a href="apage">\\1</a>', $text);

print_r($output);

See it in action.

Now the above doesn't do a very "smart" replace in the sense that the href is not a function of the matched keyword, while in practice you will probably want to do that. Look into preg_replace_callback for more flexibility here, or edit the question and provide more information regarding your goal.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • Perfect thanks does what I want, just out of interest, is there a way to only "match" the first time a keyword might occur? – Russell Parrott Sep 15 '11 at 06:51
  • @RussellParrott: Matching only the first instance of *any one* keyword is [simple](http://stackoverflow.com/questions/6729710/replace-only-first-match-using-preg-replace). Matching the first instance of *each one* keyword is not so simple; you would either need to do `preg_replace` for each one keyword with a limit of 1 in a loop or (preferably) use `preg_replace_callback`, "remember" which keywords have matched already at least once, and return the keyword itself as the replacement for those that have already been seen. – Jon Sep 15 '11 at 06:57
0

WHY would you use regex instead of just str_replace() !? Regex works, but it over complicates such an incredibly simple question.

John
  • 976
  • 1
  • 15
  • 21