Home  >  Article  >  Backend Development  >  Specified characters of variables in php regular replacement_PHP tutorial

Specified characters of variables in php regular replacement_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:44:271017browse

The following are three implementations to introduce the specified characters of variables in PHP regular substitution. Computer friends who need to learn can refer to them.

Three methods.

1.

The code is as follows Copy code
 代码如下 复制代码

$str = preg_quote('(银子)');
$txt = '我的呢称(银子)';
echo preg_replace("/($str)/","",$txt);
?>

$str = preg_quote('(silver)');

$txt = 'My nickname (silver)';
代码如下 复制代码

$str = quotemeta('(银子)');
$txt = '我的呢称(银子)';
echo preg_replace("/($str)/","",$txt);
?>

echo preg_replace("/($str)/","$1",$txt);

?>

 代码如下 复制代码
$str = '(银子)';
$txt = '我的呢称(银子)';
echo preg_replace("/(Q$strE)/","",$txt);
?>
2.

The code is as follows Copy code
$str = quotemeta('(silver)');
$txt = 'My nickname (silver)';

echo preg_replace("/($str)/","$1",$txt);

?>

 代码如下 复制代码

$text  = “foobar123fooabcbar”;

$text = preg_replace(“/foo(?=bar)/”, “***”, $text);

3.

All three methods return the same result. The Perl style regular expression in PHP is exactly the same as Perl. Even the quotemeta is universal..

 代码如下 复制代码

$text  = “foobar123fooabcbar”;

$text = preg_replace(“/(?<=bar)123/”, “***”, $text);

Some other examples of regular expressions

Example:

The code is as follows Copy code
 代码如下 复制代码

$text  = “foobar123fooabcbar”;

$text = preg_replace(“/foo(?!bar)/”, “***”, $text);

$text = “foobar123fooabcbar”; $text = preg_replace(“/foo(?=bar)/”, “***”, $text);
//Match the position in front of bar ***bar123fooabcbar
The code is as follows Copy code
$text = “foobar123fooabcbar”; $text = preg_replace(“/(?<=bar)123/”, “***”, $text);
//Match the position behind bar foo***123fooabcbar
The code is as follows Copy code
$text = “foobar123fooabcbar”; $text = preg_replace(“/foo(?!bar)/”, “***”, $text);

//Match a position that is not followed by bar foobar123***abcbar

$text = “foobar123fooabcbar”;
The code is as follows
 代码如下 复制代码

$text  = “foobar123fooabcbar”;

$text = preg_replace(“/(?

Copy code

$text = preg_replace(“/(?

//Match the position that is not foo in front of foobar123fooabc*** http://www.bkjia.com/PHPjc/633093.htmlwww.bkjia.com
true
http: //www.bkjia.com/PHPjc/633093.html
TechArticleThe following are three implementations to introduce the designated characters of variables in PHP regular substitution. For those who need to learn, Can be used for reference. Three methods. 1. The code is as follows Copy the code ?php $str = preg_qu...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn