0

Was wondering why str_replace doesn't work in my set of code, yet exploding it works.

$plate = "AAA 1234";
$plateNum = str_replace(' ', '', $plate);

$plateNum = explode(' ', $plateNum);

$updatedPlateNum = '';
foreach ($plateNum as $string) {
    $updatedPlateNum .= $string;
}

For testing purposes, "AAA 1234", the space should be omitted

edit: added $plate

Kyle
  • 105
  • 3
  • 11
  • 3
    They both seems to work fine by me, [demo](https://3v4l.org/p0OG0) – Naruto Jul 10 '19 at 08:32
  • 2
    [seems fine for me](https://phpfiddle.tk/e3a2b1d9)? Also optimised your explode - no need for a foreach – treyBake Jul 10 '19 at 08:32
  • Are there any other ALT-codes for spaces? The data was coming off of MySQL data and it might be the one that's causing the issue – Kyle Jul 10 '19 at 08:34
  • I will work just echo $plateNum = str_replace(' ', '', $plate); to check. – Shivendra Singh Jul 10 '19 at 08:41
  • Yes, there are [other white-space characters](https://en.wikipedia.org/wiki/Whitespace_character#Unicode). Also see [Can't get str_replace() to strip out spaces in a PHP string](https://stackoverflow.com/questions/16563421/cant-get-str-replace-to-strip-out-spaces-in-a-php-string) and [How can strip whitespaces in PHP's variable](https://stackoverflow.com/questions/1279774/how-can-strip-whitespaces-in-phps-variable). – showdev Jul 10 '19 at 08:42
  • use [trim](https://www.php.net/manual/en/function.trim.php) to remove extra whitespace^ – treyBake Jul 10 '19 at 08:47
  • @treyBake Only "from the beginning and end of a string". – showdev Jul 10 '19 at 08:48
  • @showdev good point.. although.. if the whitespace is in the middle of the text then there needs to be something set up insert-side to ensure that doesn't happen IMO, you shouldn't have to remove whitespaces from called data. – treyBake Jul 10 '19 at 08:48
  • Possible duplicate of [Can't get str_replace() to strip out spaces in a PHP string](https://stackoverflow.com/questions/16563421/cant-get-str-replace-to-strip-out-spaces-in-a-php-string). – showdev Jul 10 '19 at 09:57

2 Answers2

0

you can use

$plate = "AAA 1234";
$string = preg_replace('/s+/', '', $plate);
echo $string;
Rajkumar Sharma
  • 554
  • 1
  • 4
  • 9
0

Found a viable answer:

preg_replace('/\s+/u', '', $plate);

PS: I'm not literate at regex expressions which is why I was avoiding it and was using explode and str_replace.

Kyle
  • 105
  • 3
  • 11