remove single quotes followed by whitespace from a string using trim

Viewed 85

I am trying to remove whitespace and single quotes from a string.

$string = "'DZ;Algeria;The People's Democratic Republic of Algeria;Algerian'  ";
echo trim($string,"'");

In the above string I want to remove single quotes from both ends, but trim only removes the left single quote. The right side single quote remains after trimming.

The output is:

DZ;Algeria;The People's Democratic Republic of Algeria;Algerian'

But I want this:

DZ;Algeria;The People's Democratic Republic of Algeria;Algerian

4 Answers

You can trim() twice. Firstly, trim the string to remove leading and trailing spaces; and then trim again to remove leading and trailing single quotes (after removal of leading/trailing spaces)

$string = "'DZ;Algeria;The People's Democratic Republic of Algeria;Algerian'  ";
echo trim(trim($string),"'");

Demo: https://3v4l.org/0rsXN

The documentation for trim on php.net states that the second parameter:

character_mask

Optionally, the stripped characters can also be specified using the character_mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

by default, the character mask contains whitespace characters:

  • " " (ASCII 32 (0x20)), an ordinary space.
  • "\t" (ASCII 9 (0x09)), a tab.
  • "\n" (ASCII 10 (0x0A)), a new line (line feed).
  • "\r" (ASCII 13 (0x0D)), a carriage return.
  • "\0" (ASCII 0 (0x00)), the NUL-byte.
  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

If you want to trim single quotes and also the spaces before and after them, you can add the single quote to that list:

$string = "'DZ;Algeria;The People's Democratic Republic of Algeria;Algerian'  ";
echo trim($string,"' \t\n\r\0\x0B");

Otherwise, the whitespace characters are considered non-trimmable and the quote won't be removed.

If you need to keep the spaces, you will need to use preg_replace with a regular expression.

Do

$myString = " frase frase frase ";
$newString_formated = trim($myString);
echo $newString_formated;

Save it in a new variable

Related