Home > Back-end >  How to explode ignoring whit space without using regular expression
How to explode ignoring whit space without using regular expression

Time:08-01

This is my code:

<?php
$text = "A Beauti f u l Bird";
$arr = explode("Beautiful", $text);
echo $arr[0];

?>

My expected output A

CodePudding user response:

PHP considers the following characters to be whitespace:

  • The space character (" ")
  • The tab character ("\t")
  • The vertical tab character ("\v")
  • The newline character ("\n")
  • The carriage return character ("\r")
  • The null-byte character ("\x0B")

We can remove all these whitespaces inside a string using strtr function.

<?php
$text = "A Beauti f u l Bird";
$translate = array(" " => "", "\n" => "", "\t" => "", "\v" => "", "\r" => "", "\x0B" => "");
$text = strtr($text, $translate);
$arr = explode("Beautiful", $text);
echo $arr[0];
?>

CodePudding user response:

If you want to remove all spaces you can use the str_replace() function before using explode:

$text = "A Beauti f u l Bird";
$text = str_replace(" ", "", $text);
$arr = explode("Beautiful", $text);
echo $arr[0]; // "A"

This does not include whitespace characters, including newlines, carriage returns and tabs.

  •  Tags:  
  • php
  • Related