putting a pattern into a variable

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
flann
Forum Commoner
Posts: 38
Joined: Tue Aug 23, 2005 10:48 pm

putting a pattern into a variable

Post by flann »

Is it possible to use a regex to find a pattern, and then put that value into a variable?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

explain please.
flann
Forum Commoner
Posts: 38
Joined: Tue Aug 23, 2005 10:48 pm

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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).
flann
Forum Commoner
Posts: 38
Joined: Tue Aug 23, 2005 10:48 pm

Post by flann »

thank you so much :)
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Post 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
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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 ;)
Post Reply