Page 1 of 1

Preg_replace

Posted: Mon Nov 28, 2005 5:29 am
by abalfazl
Weirdan | Please use

Code: Select all

and

Code: Select all

tags where approriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]
Hello

From php.net

Code: Select all

<?php
$string = "April 15, 2003";
$pattern = "/(\w+) (\d+), (\d+)/i";
$replacement = "\${1}1,\$3";
echo preg_replace($pattern, $replacement, $string);
?>
It can be many things :$replacement = "\${1}1,\$3";

There several strings that match with this

Then How can it be replace?

Which one of those strings that match with this $replacement = "\${1}1,\$3"; replace?
there are diffrenetstrings that match with this:$replacement = "\${1}1,\$3

May you explain for me how does this function work by a simple example?

Thanks
Weirdan | Please use

Code: Select all

and

Code: Select all

tags where approriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]

Posted: Mon Nov 28, 2005 5:46 am
by n00b Saibot
May I suggest d11wtq's excellent tutorials on REGEXs :arrow: Basics and Advanced

Posted: Mon Nov 28, 2005 6:47 am
by Chris Corbyn
Regex just matches a particular pattern of characters in sequence. For example, if we had: "abc123" we could describe that as "three letters followed by three digits". The \w and \d that you see in that regex are just a more compact way of saying this. Like n00b saibot say's, you may want to read the tutorials here and also at http://regular-expressions.info

In the same way "abc123" is "three letters followed by three digits" so is "xyz678". Therefore it's the same pattern and the same regex could satisfy both.

Those are simple examples but the principles apply to everything within regex. You could think of preg_replace() as being a very clever, and very flexible version of str_replace().