phpstrpos

String replace adds extra spaces


i want to compare data from my database with new customer input. I do some modifications and somewhere is something wrong:

$result = "Südendstr. 13 a";
$healthy = array(" ");
$yummy   = array("");
$result = strval(strtolower(str_replace($healthy, $yummy, $result)));
$healthy = array("strasse", "straße",".", "str" );
$yummy   = array("str. ", "str. ", "", "str. ");
$result = strval(strtolower(str_replace($healthy, $yummy, $result)));

$_customer['customer']['adress'] = "Südendstrasse";
$healthy = array(" ");
$yummy   = array("");
$_customer['customer']['adress']  = strval(strtolower(str_replace($healthy, $yummy, $_customer['customer']['adress'] )));
$healthy = array("strasse", "straße",".", "str" );
$yummy   = array("str. ", "str. ", "", "str. ");
$_customer['customer']['adress']  = strval(str_replace($healthy, $yummy, $_customer['customer']['adress'] ));

The values are: $result = «südendstr. 13a» and $_customer['customer']['adress'] = «südendstr.»

$_strpos_1 = strpos($result, strval($_customer['customer']['adress']));
$_strpos_2 = strpos($_customer['customer']['adress'], $result);

both return false.


Solution

  • You are making - maybe unintentionally - multiple replacements in the same string, which also includes replacements that already took place. This behavior is even mentioned in the documentation of str_replace():

    Caution

    Replacement order gotcha

    Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.

    Check the following source code:

    $healthy = array("strasse", "straße",".", "str" );
    $yummy   = array("str. ", "str. ", "", "str. ");
    $tmp = str_replace($healthy, $yummy, 'südendstrasse');
    
    

    In the first run, it will replace the "strasse" with "str. ":

     "südendstrasse" ->
     "südendstr. "
    

    Then it replaces the "." with an empty string, removing it:

     "südendstr. " ->
     "südendstr "
    

    Already there you have a space at the end. And then it replaces "str" with "str. ":

     "südendstr " ->
     "südendstr.  "
    

    Now you have the resulting string "südendstr. " with two spaces at the end. And this is not in the input string "südendstr. 13a":

    "südendstr. 13a"
    "südendstr.  "
                ^
                |
                +---  (mismatch, so no position found)