Hi,

Im needing alil help with this, googled everywhere, but to no avail.
I need to search several(the amount could be endless) words in a string, and replace each word with a link using the searched-for value as the text, and id in the link.
To achieve this, I am using str_replace, but because the values within the $search array will be numerous(over 1000 quite easily). I am trying to compact the $search array so it outputs like a wildcard or variable, so i dont have to repeat a reflective value in the $replace array for each of the $search array values.

rough examples:

$search = array('value', 'value1', 'value2');// and so on and so forth
$replace = array('<a href="webpage.php?view&id=%">%</a>');
$result = str_replace($search, $replace, $string);

or

$search = array('value', 'value1', 'value2');// and so on and so forth
$replace = array('<a href="webpage.php?view&id=$search">$search</a>');
$result = str_replace($search, $replace, $string);

Or, am i not doing this the right way? I suspect I am not doing this the right way....

Any help is always appreciated. And if topic is solved, it will be marked as so.

Recommended Answers

All 2 Replies

$keywords = array('value2','value1','value');
$replace = '<a href="webpage.php?view&id=\1">\1</a>';
$search = '/('.join('|',$keywords).')/';
preg_replace($search, $replace, $source);

I've reversed the keywords because the grouping will be non-greedy so if you place 'value' first it will never find value1 or value2

:).. thank you for replying....and thanks for the tip.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.