Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Aug 2010
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question Trouble using indexed arrays along with preg_match

    Hi there. First time i post here and hope somebody will be able to help me.

    I have a file whos numbering starts at 610 and goes on to 1019. I want to use PHP's preg_match() function to start the numbering from 0 and go on till 410.

    Here is some code i've been working on. But i cant get the function to replace the numbers. I don't know why and i don't get any errors.

    <?php

    $string = "610 611 612 613 614 615 616 617"; //this isnt the actual file but will do. The actual file is more complicated. This is just a test string.

    $patterns = array();
    for ($i=610; $i<1020; $i++) {
    $patterns[$i] = '/$i/';
    }

    $replacements = array();
    for ($j=1; $j<410; $j++) {
    $replacements[$j] = '\r\n' . $j;
    }

    $newText = preg_replace($patterns, $replacements, $string);
    echo $newText;

    ?>

    I used Example #2 form http://www.php.net/manual/en/function.preg-replace.php as reference.

    Thanks in advance for any help

  • #2
    Regular Coder
    Join Date
    Jul 2010
    Posts
    185
    Thanks
    3
    Thanked 42 Times in 42 Posts
    You are actually very close.

    This should work:
    PHP Code:
    <?php

    $string 
    "610 611 612 613 614 615 616 617"//this isnt the actual file but will do. The actual file is more complicated. This is just a test string.

    $patterns = array();
    for (
    $i=610$i<1020$i++) {
    $patterns[$i] = "/$i/";
    }

    $replacements = array();
    for (
    $j=1$j<410$j++) {
    $replacements[$j] = "\r\n" $j;
    }

    $newText preg_replace($patterns$replacements$string);
    echo 
    $newText;

    ?>
    Notice how $patterns[$i] is quoted. With single quotes, PHP assigns the literal value ('/$i/' = /$i/). With double quotes, PHP will expand $i.

    You can read more on how PHP parses variables in strings here:
    http://www.php.net/manual/en/languag...string.parsing

  • #3
    New Coder
    Join Date
    Aug 2010
    Location
    India
    Posts
    42
    Thanks
    0
    Thanked 5 Times in 5 Posts
    some beautification,

    $patterns = array();
    foreach (range(610, 1019) as $number) {
    $patterns[] = $number;
    }


    Similarly for the other array.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •