tags:

views:

105

answers:

3

so if i have the text:

"this is going to be really great"

and i have the needle "goi"

i want it to find going and then replace it with the link

<a href="http://wwww.something.com/going"&gt;going&lt;/a&gt;

can you help me? i am really bad in regex

+5  A: 

You can use the following regex to match your partial needle plus the rest of the word around it:

$regex = '\b\w*' . $needle . '\w*\b';

then pass that to preg_replace:

$newtext = preg_replace($regex, '<a href="http://www.something.com/$0"&gt;$0&lt;/a&gt;', $oldtext);
Amber
You should add the capturing group and then show how to use that to build the link ;)
Franz
Doesn't actually need a capturing group - the entire match is what you'd want to use anyways.
Amber
Yeah, well, you'd still need some replace code, which you added now ;)
Franz
A: 
$str ="this is going to be really great";
$s = explode(" ",$str);
foreach($s as $k=>$v){
    if ( strpos($v,"goi") !==FALSE){
        $s[$k]= '<a href="http://wwww.something.com/' . $v . '">'. $v ."</a>";
    }
}
print_r( implode(" ",$s) );
ghostdog74
A: 
$str = preg_replace('/(\bgoi\w*)/', 
           '<a href="http://www.something.com/$1"&gt;$1&lt;/a&gt;', $str)

\b is for word boundary - without this, it will match going in ongoing

Amarghosh