preg_replace

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
Steveo31
Forum Contributor
Posts: 416
Joined: Sun Nov 23, 2003 9:05 pm
Location: San Jose CA

preg_replace

Post by Steveo31 »

I'm confused on the second parameter of preg_replace. All the examples I have seen have numbers and whatnot in em.

Could someone give me an example? I've read the manual :)
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

Simple example that replaces 'fox' with 'new fox'

Code: Select all

<?php
$string = "The quick brown fox jumped over the lazy dog.";
echo preg_replace('/fox/', 'new fox', $string);
//or do the following
//$string = preg_replace('/fox/', 'new fox', $string);
//echo $string;
?>
Steveo31
Forum Contributor
Posts: 416
Joined: Sun Nov 23, 2003 9:05 pm
Location: San Jose CA

Post by Steveo31 »

Huh.. simpler than I thought.

So then what would be all this garbled stuff?

Code: Select all

function MakeUrl($strUrl)
{
   $strUrl = preg_replace("/(http(s)?:\\/\\/[^\\s\\n]*)\\b(\\/)?/i","<a href="\\\\0">\\\\0</a>",$strUrl);
   return $strUrl;
}
I understand regex in terms of matching, but escaping \ and adding numbers is throwing me waaaay off base.

Thanks mark
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

You can't really explain regex on a forum, have to google for 'regex tutorial' ... it's a massive subject.
User avatar
tim
DevNet Resident
Posts: 1165
Joined: Thu Feb 12, 2004 7:19 pm
Location: ohio

Post by tim »

Steveo31
Forum Contributor
Posts: 416
Joined: Sun Nov 23, 2003 9:05 pm
Location: San Jose CA

Post by Steveo31 »

Afraid of that. Thanks mark and tim for the link :D
Post Reply