Page 1 of 1

Need PHP Reg Expression preg_replace help

Posted: Tue Aug 30, 2011 11:34 pm
by mar2195
The FULL STRING passed in has the variable: $message;

I am trying to find:
#string1_with_nums_and_chars
and
@string2_with_nums_and_chars

Then, each time one of these characters is found, it will be replaced by it's own URL.

Example Output for #:
<a href="http://www.somesite.com/something?q=str ... d_chars</a>

Example Output for @:
<a href="http://www.somesite.com/watch?string2_w ... d_chars</a>

The length of each string is unknown and the string's are dynamic.

Re: Need PHP Reg Expression preg_replace help

Posted: Wed Aug 31, 2011 4:42 pm
by genix2011
Hi,

this can be done by using preg_replace, here the code:

Code: Select all

<?php

//regex #string1_with_nums_and_chars
$regex1 = "/#([a-zA-Z0-9]+)/";
$replace1 = "<a href=\"http://www.somesite.com/something?q=$1\">$0</a>";

//regex @string2_with_nums_and_chars
$regex2 = "/@([a-zA-Z0-9]+)/";
$replace2 = "<a href=\"http://www.somesite.com/watch?q=$1\">$0</a>";

$string = "#koko2837 Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
Ut enim ad minim veniam, @feeeeefquis nostrud exercitation ullamco laboris nisi ut aliquip 
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit 
esse cillum dolore eu fugiat nulla #pwfwefariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

$replaced_string = preg_replace(array($regex1, $regex2), array($replace1, $replace2), $string);

echo $replaced_string;
?>
Greets.