Home >Backend Development >PHP Problem >How to remove single quotes from string in php
Two implementation methods: 1. Use str_replace() to replace all single quotes in the string with empty characters, the syntax is "str_replace("'","", string)"; 2. Use preg_replace() to execute the regular expression "/\'/" to search for all single quotes in the string and replace them with empty characters. The syntax is "preg_replace("/\'/","", characters string)".
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
In php, you can use the str_replace() function Or preg_replace() function to remove single quotes in the string, just replace the single quotes in the string with null characters.
Method 1: Use the str_replace() function to replace single quotes in the string with empty characters
str_replace() function replaces some characters in the string (size-sensitive Write).
str_replace(find,replace,string,count)
Parameters | Description |
---|---|
find | Required . Specifies the value to look for. |
replace | Required. Specifies a value that replaces the value in find. |
string | Required. Specifies the string to be searched for. |
count | Optional. A variable counting the number of substitutions. |
# Just set the first parameter to a single quote "'" and the second parameter to a null character.
<?php header('content-type:text/html;charset=utf-8'); $str = "My name is 'LiHua','20' years old!"; echo "原字符串:".$str."<br>"; $new = str_replace("'","",$str); echo "去除单引号后:".$new; ?>
Method 2: Use the preg_replace() function with the regular expression /\'/
to replace the single quotes in the string with Null character
preg_replace function performs a regular expression search and replace.
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
Search for the part matching pattern in subject and replace it with replacement.
Parameter description:
$pattern: The pattern to be searched, which can be a string or a string array.
$replacement: String or array of strings used for replacement.
$subject: The target string or string array to be searched and replaced.
$limit: Optional, the maximum number of substitutions for each subject string per pattern. The default is -1 (no limit).
$count: Optional, the number of times the replacement is performed.
Just use the preg_replace() function to execute the regular expression /\'/
to search for all single quotes in the string and replace them with empty Just use the characters
<?php header('content-type:text/html;charset=utf-8'); $str = "My name is 'LiHua','20' years old!"; echo "原字符串:".$str."<br>"; $new = preg_replace("/\'/","",$str); echo "去除单引号后:".$new; ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to remove single quotes from string in php. For more information, please follow other related articles on the PHP Chinese website!