PHP replace only first occurrence of a string match.

How to replace only the first occurrence of a string in php.

Say you wanted to only replace the first occurrence of a string match instead of all occurrences You would use php preg_replace function to do the trick.

The code is below:

<?
$var = 'abcdef abcdef abcdef';
// pattern, replacement, string, limit
echo preg_replace('/abc/', '123', $var, 1); // outputs '123def abcdef abcdef'
?>

Just incase you wanted to still match all occurrences, just use the php function erag_replace.
The code is below:


<?
$var = 'abcdef abcdef abcdef';
// pattern, replacement, string
echo ereg_replace('abc', '123', $var); // outputs '123def 123def 123def'
?>

You may also like...

12 Responses

  1. Jake says:

    Nice. So simple, but way more useful then trying to figure out string positions in order to isolate only the first. Thanks for the tip.

  2. jammboo says:

    What if I want to bold the first occurrence of a word in a description? I tried using:

    <?
    // $description holds the entire description
    ereg_replace($keyword, '‘.$keyword.’‘, $description);
    ?>

    And I get an error: “Warning: Wrong parameter count for ereg_replace()”

  3. jammboo says:

    Looks like it actually bolded on your website… odd… I got rid of the 1 at the end of the parameters and it works. Does this only work with an old version of PHP or something?

  4. Worked like a charm! Thanks a lot man – comes in handy all the time when playing with WordPress content.

  5. Homeschool says:

    I am using a replace function so I can create an unordered list. Problem is I need to ignore the first occurance because I start my list and then use the replace to close and start the lists.

    Thankfully, I found your post to help me replace the first occurance of a match in the string! Worked just like I needed it to!

  6. Andrey says:

    And what should I do, when I need to replace symbol “?”, can you say?

    • admin says:

      Use the str_replace function. For example:
      // not sure if you need to escape (\) the question mark symbol
      str_replace(“\?”,”new symbol”,$text);
      or
      str_replace(“?”,”new symbol”,$text);

  7. Mould Maker says:

    Pretty good article . Thank you for your sharing. I just figure out the problem.

  8. jayjay says:

    Hi there admin, just a bit of curiosity 🙂 I’m trying to replace a char on the last text in the string but keep appending to each, so far I’ve coded:
    $var = ‘abcdef abcdef abcdef’;
    echo preg_replace(‘/f/’, ‘Z’, $var, strlen($var)-1); //returns: abcdeZ abcdeZ abcdefZ

    but requiring: abcdef abcdef abcdeZ

    any insight on this one? cheers~:)

  9. jayjay says:

    Hi there, solution found, no prob’s! 🙂
    passed var in to an array with a foreach loop – handy for string phasing in loops,
    x2 birds – one stone! 😉
    then just a matter of imploding back to variables.

    below, working code for generating an array from variables to search-replace the last character in the last occurrence of strings.
    =====================================================================
    $arr = array(“apples taste delicious,”, “oranges are sweet,”, “lettuce tastes crunchy,”, “bananas are nice in deserts,”, “pears are tasty!,”, “mangoes are great for breakfast,”);
    foreach ($arr as &$val){
    $val[strlen($val)-1] = “Z”;
    $val = ($val. PHP_EOL);
    }
    unset($v);
    $var = implode(“”, $arr);
    echo $var;
    =====================================================================
    Some food for coding thought: If calling $arr = file(“list-of-fruits.txt”); you will will need to set the negative coordinate (read-backward coordinate) to -3
    ie: $val[strlen($val)-3] = “Z”;

    This is what stomped me for while as I thought I was miss-targeting the last character in the string. Array’s generated from a text file carry excessive white space which tricks php (and the observer) into seeing what appears to be the replacement character appended to the back of a string in an array.

    php is merry replacing the last white space behind the values, Something to definitely consider if your manipulating values in and array.!

    below, working code for generating an array from text file to search-replace the last character in the last occurrence of strings.
    (assuming your info lists it’s sentences line by line)
    =====================================================================
    $arr = array(“list-of-fruits.txt”);
    foreach ($arr as &$val){
    $val[strlen($val)-3] = “Z”;
    }
    unset($v);
    $var = implode(“”, $arr);
    echo $var;
    =====================================================================

    Hope it help you as it did for me! enjoy~ 😉

  10. jayjay says:

    whoops only human coding of the top of my head again 😉
    unset($v);
    should of been –> unset($val);

    proves I’m human after all!

    🙂 🙂

  11. Salafy says:

    Thank you, this replace php fuction, very useful for me.

Leave a Reply