php 简单的 preg_replace
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1487064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple preg_replace
提问by bluedaniel
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.
我根本无法弄清楚 preg_replace ,它对我来说只是中文,无论如何我只需&page-X要从字符串中删除“ ”,如果它在那里。
Xbeing a number of course, if anyone has a link to a useful preg_replacetutorial for beginners that would also be handy!
X当然,如果有人有指向preg_replace初学者有用教程的链接,那也会很方便!
回答by Ferdinand Beyer
Actually the basic syntax for regular expressions, as supported by preg_replaceand friends, is pretty easy to learn. Think of it as a string describing a pattern with certain characters having special meaning.
实际上,正则表达式的基本语法,正如preg_replace朋友们所支持的那样,非常容易学习。将其视为描述具有特殊含义的某些字符的模式的字符串。
In your very simple case, a possible pattern is:
在您非常简单的情况下,可能的模式是:
&page-\d+
With \dmeaning 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.
有了\d这意味着一个数字(数字字符0-9)和+意为:前重复表达权+(此处\d)一次或多次。所有其他角色只代表他们自己。
Therefore, the pattern above matches any of the following strings:
因此,上面的模式匹配以下任何字符串:
&page-0
&page-665
&page-1234567890
Since the pregfunctions use a Perl-compatible syntax and regular expressions are denoted between slashes (/) in Perl, you have to surround the pattern in slashes:
由于preg函数使用与 Perl 兼容的语法,并且正则表达式/在 Perl中用斜线 ( )表示,因此您必须将模式括在斜线中:
$after = preg_replace('/&page-\d+/', '', $before);
Actually, you can use other characters as well:
实际上,您也可以使用其他字符:
$after = preg_replace('#&page-\d+#', '', $before);
For a full reference of supported syntax, see the PHP manual.
有关受支持语法的完整参考,请参阅PHP 手册。
回答by Gumbo
preg_replaceuses Perl-Compatible Regular Expressionfor the search pattern. Try this pattern:
preg_replace使用Perl 兼容的正则表达式作为搜索模式。试试这个模式:
preg_replace('/&page-\d+/', '', $str)
See the pattern syntaxfor more information.
有关更多信息,请参阅模式语法。
回答by Marius
回答by TigerTiger
preg_replace('/&page-\d+/', '', $string)
Useful information:
有用的信息:
Using Regular Expressions with PHP
http://articles.sitepoint.com/article/regular-expressions-php
http://articles.sitepoint.com/article/regular-expressions-php

