简体   繁体   中英

How to remove double quotes from a string

This is my string:

$a='"some text';`

How can I remove the double quote so my output will look like this?

some text`

str_replace()

echo str_replace('"', '', $a);

if string is: $str = '"World"';

ltrim() function will remove only first Double quote.

Output: World"

So instead of using both these function you should use trim() . Example:

$str = '"World"';
echo trim($str, '"');

Output-

World

Probably makes the most sense to use ltrim() since str_replace() will remove all the inner quote characters (depends, maybe that's what you want to happen).

ltrim — Strip whitespace (or other characters) from the beginning of a string

echo ltrim($string, '"');

If you want to remove quotes from both sides, just use regular trim() , the second argument is a string that contains all the characters you want to trim.

使用str_replace

$a = str_replace('"', '', $a);

There have two ways you can remove double quotes also third brackets from an array string.

Sample 1:

$ids = ["1002","1006","1005","1003","1004"];
$string = str_replace(array('[',']'),'',$ids);
$newString = preg_replace('/"/i', '', $string);
return $newString;

Sample 2:

function removeThirdBrackets($string)
 {
    $string = str_replace('[', '', $string);
    $string = str_replace(']', '', $string);
    $string = str_replace('"', '', $string);
    return $string;
 }

Output:

1002,1006,1005,1003,1004

There are different functions are available for replacing characters from string below are some example

    $a='"some text';
    echo 'String Replace Function<br>';
    echo 'O/P : ';
    echo $rs =str_replace('"','',$a);
    echo '<br>===================<br>';
    echo 'Preg Replace Function<br>';
    echo 'O/P : ';  
    echo preg_replace('/"/','',$a);
    echo '<br>===================<br>';
    echo 'Left Trim Function<br>';
    echo 'O/P : ';  
    echo ltrim($a, '"');
    echo '<br>===================';

Here is the O/P

输出图像

You can do this:

str_replace()
echo str_replace('\"', '', $a);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM