Jump to content

using preg_replace()


dsaba

Recommended Posts

trying to understand how to use preg_replace()

I read this in the manual:

<?php
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string);
?>

 

the output of that sample regex is:

Array
(
    [0] => Array
        (
            [0] => April 15, 2003
        )

    [1] => Array
        (
            [0] => April
        )

    [2] => Array
        (
            [0] => 15
        )

    [3] => Array
        (
            [0] => 2003
        )

)

 

 

now seeing the example I want to do something similar with this code I made up:

<?php
$str = '$var = -34;
if ($this == -134) {
$x = 5 - -9;
$b = 7 + -9832;
$notThis = 8 - 10;
$again = 1234-1234;
$here = -9 + 78;
}';
$pat = '~[-+=](| )(-)[0-9]+~';
preg_match_all($pat, $str, $out);
preg_replace($pat, '${2}negative', $str);
output($out,100,100);
output($str, 100,100);
?>

 

I get this output for the $out:

Array
(
    [0] => Array
        (
            [0] => = -34
            [1] => = -134
            [2] => - -9
            [3] => + -9832
            [4] => = -9
        )

    [1] => Array
        (
            [0] =>  
            [1] =>  
            [2] =>  
            [3] =>  
            [4] =>  
        )

    [2] => Array
        (
            [0] => -
            [1] => -
            [2] => -
            [3] => -
            [4] => -
        )

)

 

I get this output for the changed $str with preg_replace

$var = -34;
if ($this == -134) {
$x = 5 - -9;
$b = 7 + -9832;
$notThis = 8 - 10;
$again = 1234-1234;
$here = -9 + 78;
}

 

 

So you see preg_replace() did not change anything! Apparently I'm not using it correctly. My regex grabs all negative signs, take note I said negative signs and not subtraction signs. I simply want to replace all negative signs in the $str string with the string 'negative'

 

The captured negative signs with my regex can be seen in $out[2]

So how can I replace these matched negative signs with the string 'negative' with the preg_replace() function?

Also if there is a better way to write my regex pattern for matching negative signs, let me know. I couldn't find a way to say '' or ' ' , (space or null) I used (| ), if i didnt' use the parenthesis it wouldn't catch it, however by using parenthesis it also thinks its a substring, and spits it out in $out[1] which is just a waste, because i'm not really looking for that substring, just the negative

 

Thanks for reading

Link to comment
Share on other sites

haystack

$var = -34;

if ($this == -134) {

$x = 5 - -9;

$b = 7 + -9832;

$notThis = 8 - 10;

$again = 1234-1234;

$here = -9 + 78;

}

 

regex

/([ ]\-)(?!([ ]\-|[ ][0-9]))/

 

replace with (note there is a space in front of negative)

negative

 

Result

$var = negative34;

if ($this == negative134) {

$x = 5 - negative9;

$b = 7 + negative9832;

$notThis = 8 - 10;

$again = 1234-1234;

$here = negative9 + 78;

}

 

Here is the command

$output = preg_replace(/([ ]\-)(?!([ ]\-|[ ][0-9]))/, negative,$var = -34; if ($this == -134) { $x = 5 - -9; $b = 7 + -9832; $notThis = 8 - 10; $again = 1234-1234; $here = -9 + 78; });

Link to comment
Share on other sites

your command came up with a parse error

but the format was like this:

preg_replace(PATTERN, 'negative', HAYSTACK);

                                ^^^

                              here is my source of confusion

 

in the manual example they do something like this:

$replacement = '${1}1,$3';

 

how this special format of  { } brackets and $ dollar sign works I don't know

you did none of this for the replacement, and it came up with a parse error anyways..

so...?

 

 

from my original post you can see my attempt:

${2}negative

why I chose 2 ? because in $out[2] are the captured substrings of negative signs in my original regex

 

Link to comment
Share on other sites

in the manual example they do something like this:

$replacement = '${1}1,$3';

 

ok, up in the Replacement notes of the of doc for preg_replace you will see that in this case they want a litteral 1 after the replace $1

so then needed to set the $1 apart from being look at as $11

 

The $1 and $3 match the parens in the PATTERN '/(\w+) (\d+), (\d+)/i', so $1 = what is returned with (\w+) and $3 = (\d+)/i

 

Ok here is a revised, the code using the $# and this I wrapped the first space with parens

so

$1 = ([ ])

$2 = (\-)

the rest is look ahead code (?!([ ]\-|[ ][0-9]))

 

so using this REPLACE - $1$2~negative~

I am restoring the (space) and the (-) in front of string ~negative~

 

Haystack

$var = -34;
if ($this == -134) {
   $x = 5 - -9;
   $b = 7 + -9832;
   $notThis = 8 - 10;
   $again = 1234-1234;
   $here = -9 + 78;
}

 

Patern

/([ ])(\-)(?!([ ]\-|[ ][0-9]))/

 

Replace

$1$2~negative~

 

Result

$var = -~negative~34;
if ($this == -~negative~134) {
   $x = 5 - -~negative~9;
   $b = 7 + -~negative~9832;
   $notThis = 8 - 10;
   $again = 1234-1234;
   $here = -~negative~9 + 78;
}

 

Code (and this time ill add the quotes ;-))

$output = preg_replace('/([ ])(\-)(?!([ ]\-|[ ][0-9]))/','$1$2~negative~','$var = -34; if ($this == -134) { $x = 5 - -9; $b = 7 + -9832; $notThis = 8 - 10; $again = 1234-1234; $here = -9 + 78; }');

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.