- 文档地址
- 不过作为一个初学者又不是很聪明的我,一开始是没有看懂文档的说明的,所以我决定自己记录下
- preg_replace()该函数接收三个参数
参数 | 作用 |
---|---|
pattern | 正则表达式或者要匹配的内容 |
replacement | 要替换的内容 |
subject | 要操作的对象 |
- 示例
<?php
$num = '4';
$string = "This string has four words.";
$string = preg_replace('/four/',$num, $string);
echo $string; #This string has 4 words.
?>
- 正则表达式的情况我就不再具体写了,主要是想说明下上面的
/four/
左右两边的/
,实验结果如下- 这部分为要匹配的内容,在匹配内容的开头和结尾必须要添加同样的标识,但是不能为数字和字母,否则报如下错:
PHP Warning: preg_replace(): Delimiter must not be alphanumeric or backslash in /box/main.php
- 也可以不是
/
,开头和结尾的标识是其他的符号也可以,只要两个相同就OK,如:
<?php $num = '4'; $string = "This string has four words."; $string = preg_replace('@four@',$num, $string); echo $string; # This string has 4 words. ?>