Page 1 of 1

putting a pattern into a variable

Posted: Mon Feb 13, 2006 2:48 pm
by flann
Is it possible to use a regex to find a pattern, and then put that value into a variable?

Posted: Mon Feb 13, 2006 3:09 pm
by feyd
explain please.

Posted: Mon Feb 13, 2006 3:19 pm
by flann

Code: Select all

<?
 $variable = 'this is a message that has a link in it. http://www.ourlacrosse.com';

 $url = 'www\\.[a-z]+\\.com'; \\ I want to find any urls and put them into a variable.

 print ("<a href='$url'>$url</a>"); \\ Then I want to be able to make the url a link.
I can figure out most of this, I just need to know how to use a regex to find the pattern (url) and then put that pattern into a variable or array.

Posted: Mon Feb 13, 2006 3:26 pm
by feyd
preg_replace() can do that for you, if you want to do it inline.

Code: Select all

$newstring = preg_replace('#((?:http://)?(www\.[a-z]+\.com))#','<a href="http://\\2">\\1</a>',$string);
If you simply want found string, you can use the same pattern with preg_match()/preg_match_all() and supply the $matches argument (last one possible).

Posted: Mon Feb 13, 2006 3:31 pm
by flann
thank you so much :)

Posted: Mon Feb 13, 2006 3:32 pm
by josh
Yes, just provide a variable where you want the matches to be send as the 4th paramater to preg_match

Code: Select all

If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.

Edit
~~~~~~~~~~~~~~
Left the thread open for too long, didn't know this was already solved

Posted: Mon Feb 13, 2006 3:42 pm
by Chris Corbyn
Be sure to have a read of the stickies at the top of this Regex board ;) They're pretty speedy but cover all that stuff ;)