[英]replacing a string with preg_replace
I have a URL like this: 我有这样的网址:
http://Example.com/mobile-ds-cams/mobile-gg-cams/ddd-webcams
Example: 例:
$pattern = '/http://Example.com/(\w+)/(\w+)/(\w+)/i';
$replacement="http://Example.com/$2/$3";
$appUrl= preg_replace($pattern, $replacement, $appUrl);
What I want to achieve is this 我要实现的是
http://Example.com/mobile-gg-cams/ddd-webcams
I am trying to keep 2 "sub-URLs" instead of 3. but it doesn't work..why? 我正在尝试保留2个“子URL”而不是3个,但这不起作用..为什么?
You need to escape your forward-slashes within the pattern, or use different pattern delimiters. 您需要在模式中转义正斜杠,或使用其他模式定界符。
$pattern = '/http:\/\/Example\.com\/(\w+)\/(\w+)\/(\w+)/i';
$pattern = '#http://Example\.com/(\w+)/(\w+)/(\w+)#i';
Escape the slashes like this: 像这样转义斜线:
$pattern = '/http:\/\/Example.com\/(\w+)\/(\w+)\/(\w+)/i';
$replacement="http://Example.com/$2/$3";
$appUrl= preg_replace($pattern, $replacement, $appUrl);
It doesn't work correctly because your expression contains characters with special meaning in a regex that have not been properly quoted. 它不能正常工作,因为您的表达式在正则表达式中包含具有特殊含义的字符,但未正确对其加引号。
To be 100% certain, use preg_quote
like this: 要100%确定, preg_quote
像这样使用preg_quote
:
$url = 'http://Example.com/'
$pattern = preg_quote($url.'{word}/{word}/{word}', '/');
$pattern = str_replace($pattern, '{word}', '(\w+)');
$pattern = "/$pattern/i";
$replacement = $url.'$2/$3';
$appUrl= preg_replace($pattern, $replacement, $appUrl);
Otherwise, it's simply too easy to get things wrong. 否则,很容易出错。 For example, all of the other answers currently posted here get it wrong because they do not properly escape the .
例如,当前在此处发布的所有其他答案都将其弄错了,因为它们不能正确地转义.
in Example.com
. 在Example.com
。 You can test this yourself if you feed them a string like eg http://Example!com
, where !
如果您向他们提供诸如http://Example!com
类的字符串,则可以自己测试一下!
can be any character you like. 可以是您喜欢的任何字符。
Additionally, you are using strings such as $2
inside a double-quoted string literal, which is not a good idea in PHP because IMHO it's easy to get carried away. 此外,您在双引号字符串文字中使用了诸如$2
字符串,在PHP中这不是一个好主意,因为恕我直言,它很容易被拿走。 Better make that singly quoted and be safe. 最好将其单独引用并保持安全。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.