Remove Quotes from String in PHP

1. Remove Quotes from String in Php

1.1 Using str_replace() Method

Use the str_replace() function to remove quotes from String in PHP.

We used str_replace() to remove double quotes and single quotes from the String.

str_replace() replaces all instances of search string with replacement String. It takes three arguments:
the string to search : single quote or double quote
the string to replace, empty space
the string to be searched: Input String

str_replace() returns a new String, it does not change contents of original String.

if you want to remove both single quotes and double quotes in one call, Use below code:

1.2 Using preg_replace() Method

Use the preg_replace() function to remove quotes from String in PHP.

We used preg_replace() with regular expression /['\"]+/ to remove double quotes and single quotes from the String.

Here is image which represents regex:
Remove all quotes from String in PHP
preg_replace() function takes a regular expression as an argument and replaces all matches with the specified string

preg_replace() replaces all instances of search pattern with replacement String. It takes three arguments:
regular expression : "/['\"]+/"
the string to replace, empty space
the string to be searched: Input String

preg_replace() returns a new String, it does not change contents of original String.

2. Remove Quotes from Beginning and End of String in Php

In case, you need to remove quotes only from beginning and end of the String, there are multiple ways to do it.

2.1 Using trim() Method

Use trim() method to remove quotes from beginning and end of the String.

We used trim() method to remove quotes from beginning and end of String.

trim() method removes characters from beginning and end of a String.

2.2 Using preg_Replace() Method

Use preg_replace with regular expression '/^(\'(.*)\'|"(.*)")$/' to remove quotes from beginning and end of the String.

Here is image which represents regex:
Remove quotes from String in PHP

That’s all about how to remove quotes from String in PHP.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *