How To Remove Quotes From String In Php

When working with strings in PHP, you may come across situations where you need to remove quotes (either single or double) from a string. This can be achieved using PHP’s built-in string manipulation functions. In this blog post, we’ll discuss different ways to remove quotes from a string in PHP.

Method 1: Using str_replace function

The str_replace function can be used to replace all occurrences of a search value with a replacement value in a given string. To remove quotes from a string, you can use the str_replace function to replace both single and double quotes with an empty string.

$string = 'This is a "test" string with \'quotes\'.';
$no_quotes = str_replace(array('"', "'"), '', $string);
echo $no_quotes; // Output: This is a test string with quotes.

Method 2: Using strtr function

The PHP strtr function can be used to translate characters or replace substrings. To remove quotes from a string, you can use the strtr function with a translation table that replaces single and double quotes with empty strings.

$string = 'This is a "test" string with \'quotes\'.';
$no_quotes = strtr($string, array('"' => '', "'" => ''));
echo $no_quotes; // Output: This is a test string with quotes.

Method 3: Using preg_replace function

The preg_replace function is a powerful tool for searching and replacing text using regular expressions. To remove quotes from a string, you can use the preg_replace function with a regular expression that matches single and double quotes and replaces them with an empty string.

$string = 'This is a "test" string with \'quotes\'.';
$no_quotes = preg_replace('/["\']/', '', $string);
echo $no_quotes; // Output: This is a test string with quotes.

Conclusion

In this blog post, we’ve covered three different ways to remove quotes from a string in PHP using the str_replace, strtr, and preg_replace functions. Each of these methods has its own advantages, so you can choose the one that best fits your requirements. Happy coding!