简单的 preg_replace [英] Simple preg_replace
问题描述
我根本无法弄清楚 preg_replace,它对我来说只是中文,无论如何我只需要从字符串中删除&page-X
"(如果它在那里).
I cant figure out preg_replace at all, it just looks chinese to me, anyway I just need to remove "&page-X
" from a string if its there.
X
当然是一个数字,如果有人有一个链接到一个有用的 preg_replace
初学者教程,那也会很方便!
X
being a number of course, if anyone has a link to a useful preg_replace
tutorial for beginners that would also be handy!
推荐答案
实际上,preg_replace
和朋友支持的正则表达式的基本语法非常容易学习.将其视为描述具有特殊含义的某些字符的模式的字符串.
Actually the basic syntax for regular expressions, as supported by preg_replace
and friends, is pretty easy to learn. Think of it as a string describing a pattern with certain characters having special meaning.
在您非常简单的情况下,可能的模式是:
In your very simple case, a possible pattern is:
&page-\d+
其中 \d
表示数字(数字字符 0-9)和 +
表示:在 +
之前重复表达式(此处:\d
) 一次或多次.所有其他角色都代表他们自己.
With \d
meaning a digit (numeric characters 0-9) and +
meaning: Repeat the expression right before +
(here: \d
) one or more times. All other characters just represent themselves.
因此,上面的模式匹配以下任何字符串:
Therefore, the pattern above matches any of the following strings:
&page-0
&page-665
&page-1234567890
由于 preg
函数使用与 Perl 兼容的语法,并且正则表达式在 Perl 中用斜杠 (/
) 表示,因此您必须将模式括在斜杠中:
Since the preg
functions use a Perl-compatible syntax and regular expressions are denoted between slashes (/
) in Perl, you have to surround the pattern in slashes:
$after = preg_replace('/&page-\d+/', '', $before);
实际上,您也可以使用其他字符:
Actually, you can use other characters as well:
$after = preg_replace('#&page-\d+#', '', $before);
有关受支持语法的完整参考,请参阅 PHP 手册.
For a full reference of supported syntax, see the PHP manual.
这篇关于简单的 preg_replace的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!