Need PHP Reg Expression preg_replace help

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mar2195
Forum Newbie
Posts: 1
Joined: Tue Aug 30, 2011 11:18 pm

Need PHP Reg Expression preg_replace help

Post 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.
genix2011
Forum Commoner
Posts: 74
Joined: Tue Aug 02, 2011 4:00 pm

Re: Need PHP Reg Expression preg_replace help

Post 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.
Post Reply