not understanding pattern matching [message #178609] |
Wed, 11 July 2012 22:35  |
Michael Joel
Messages: 42 Registered: October 2011
Karma: 0
|
Member |
|
|
I am wanting to change words in a string that has special tags.
Ex. "This is a %/i%special%i% word in the string."
If I want to replace any word between the %/i% and %i% what would I do?
I messed with preg_repace but I couldn't understand the pattern system.
Mike
|
|
|
|
|
|
|
|
|
|
Re: not understanding pattern matching [message #178620 is a reply to message #178614] |
Fri, 13 July 2012 03:22  |
Denis McMahon
Messages: 634 Registered: September 2010
Karma: 0
|
Senior Member |
|
|
On Wed, 11 Jul 2012 19:31:12 -0400, Michael Joel wrote:
> I was trying to just first get it to replace the exact thing typed. Then
> move on to replacing any word within the %/i% and %i%
>
> $Scripture="this is a %/i%test%i%";
> preg_replace("%/i%test%i%","XXXXXXXX",$Scripture);
>
> This errors with Unknown modifier t I tried what I thought was escaping
> it by putting a \test but that just messes up more. See I haven't a
> clue.
http://php.net/manual/en/regexp.reference.delimiters.php
When you use a regex, the first character inside your quotes is taken as
the pattern delimiter.
In your case, this is a "%" character.
The format of a regex string is:
"delimiter pattern delimiter optional-modifiers"
Hence, "%/i%t" is the pattern "/i" with the modifier "t"
Try:
preg_replace("!%/i%test%i%!","XXXXXXXX",$Scripture);
This will use the "!" character as the pattern delimiter and should, in
this specific case, solve your problem. Generally it's a good idea to
pick a pattern delimiter that does not have special meaning to regex and
is not part of your data. This isn't always easy.
Rgds
Denis McMahon
|
|
|