Jump to content

RegEx - preg_replace 1 or 0 to Yes or No


aalcantara

Recommended Posts

preg_replace offers conditions but not really in the way you are looking to do.  Basically the way regex conditions work is you can test if a previous capture took part of a match, and if so, continue with this pattern, or else continue with this other pattern.  For something like what you are wanting to do, php does not support that.  You will have to do multiple regexes inside regular php conditions (if necessary).

 

Like in your case, you could just do 2 separate regexes:

 

$string = preg_replace('~1~','Yes',$string);

$string = preg_replace('~0~','No',$string);

 

I think possibly Perl might support integrating conditions inside pattern matching, if that's an option for you. 

In PCRE, the conditional syntax basically follows along the lines of (?if then | else). So inline with what CV mentioned, it won't serve in the context you seek.

The conditional aspect is with regards to captures.. 'if this is captured, then look for that' kind of thing.

 

Example:

//$str = 'Two blind mice.';
$str = 'Blind mouse.';
if(preg_match('#(two )?blind (?(1)mice|mouse).#i', $str)){
   // either 'Two blind mice.' or 'Blind mouse.' found! (case insensitive)
}

 

Bascially, The begining of the pattern looks for two[space] (but optional, as the questionmark afterwards dictates). Since this is a capture, if found will be stored under $1. After blind[space] in the pattern, we arrive at the conditional - (?(1)mice|mouse). It basically says, if the first capture exists (and it will if two[space] if found before blind[space]), at this position in the string, look to see if 'mice' is matched.. if the first capture doesn't exist, look to see if 'mouse' is found instead.

 

Granted, I think one could also use only the if or else component if I'm not mistaken when dealing with conditionals.In your case, you could use str_replace or perhaps even strtr as two additional examples instead of preg_replace (yes, I know, you were interested in regex explicitly).

Using the e modifier, the replacement is treated as PHP. I know it's not pure regular expressions, but it's done within a single preg_replace() call:

 

<?php
$str = '00100100';
echo preg_replace('~[01]~e', "$0 ? 'Yes' : 'No'", $str);
//NoNoYesNoNoYesNoNo
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.