以下情况如何正确使用preg_replace?
How to use preg_replace correct in the following case?
我希望有人能帮助我一些“preg_replace”技巧。
我有以下 URL:
http://www.domain.com/goto/test-string/
现在我只想获取 URL 的“测试字符串”部分。
知道如何用 preg_replace 解决这个问题吗?
提前致谢!!!
最好的,
弗洛里安
我建议使用 parse_url()
来获取碎片:
http://php.net/manual/en/function.parse-url.php
然后根据需要使用explode( '/', $sUrl );
获取字符串。
http://php.net/manual/en/function.explode.php
对于动态解析,您可能需要进行更多调整。
看来 preg_match()
更适合您:
if (preg_match('/([^/]*)/$', $url, $m) {
echo "The string you are looking for is $m[1]<br />\n";
}
但是因为你特别要求 preg_replace()
我想你可以这样做:
$foo = preg_replace('/^.*?/([^/]*)/$/', '', $url);
编辑:我忘记在正则表达式中转义我的斜线。更容易用管道符号替换正则表达式描述符,这样斜线就不再特殊了。
$foo = preg_replace('|^.*?/([^/]*)/$|', '', $url);
请试试这个..
$url = 'http://www.domain.com/goto/test-string/hi/';
preg_match('/.*\/(.*?)\//',$url,$match);
echo $match[1];
我希望有人能帮助我一些“preg_replace”技巧。
我有以下 URL: http://www.domain.com/goto/test-string/
现在我只想获取 URL 的“测试字符串”部分。 知道如何用 preg_replace 解决这个问题吗?
提前致谢!!!
最好的, 弗洛里安
我建议使用 parse_url()
来获取碎片:
http://php.net/manual/en/function.parse-url.php
然后根据需要使用explode( '/', $sUrl );
获取字符串。
http://php.net/manual/en/function.explode.php
对于动态解析,您可能需要进行更多调整。
看来 preg_match()
更适合您:
if (preg_match('/([^/]*)/$', $url, $m) {
echo "The string you are looking for is $m[1]<br />\n";
}
但是因为你特别要求 preg_replace()
我想你可以这样做:
$foo = preg_replace('/^.*?/([^/]*)/$/', '', $url);
编辑:我忘记在正则表达式中转义我的斜线。更容易用管道符号替换正则表达式描述符,这样斜线就不再特殊了。
$foo = preg_replace('|^.*?/([^/]*)/$|', '', $url);
请试试这个..
$url = 'http://www.domain.com/goto/test-string/hi/';
preg_match('/.*\/(.*?)\//',$url,$match);
echo $match[1];