我无法使regexp和preg_replace工作

时间:2012-01-13 20:18:17

标签: php

为什么这不能输出任何想法?

我只想删除/ page / *部分网址。

即使字符串包含更长的网址,我的目标也是始终http://www.sandrophoto.com/category/car-photography/

我试过了:

<?php

$url1 = "http://www.sandrophoto.com/category/car-photography/page/1/";
$url2 = "http://www.sandrophoto.com/category/car-photography/page/2/";
$url3 = "http://www.sandrophoto.com/category/car-photography/";

$cleaned1 = preg_replace('/page/*', '', $url1);
$cleaned2 = preg_replace('/page/*', '', $url2);
$cleaned3 = preg_replace('/page/*', '', $url3);

echo "$cleaned1 <br>";
echo "$cleaned2 <br>";
echo "$cleaned3 <br>";

?>

1 个答案:

答案 0 :(得分:1)

正则表达式需要分隔符,而您没有使用分隔符。此外,正斜杠后面跟一个星号表示“零或多个正斜杠”,当你想要“正斜杠后跟零或更多非换行符”时,这将是/.*

preg_replace('/page/*', '', $url1);

应该是

preg_replace('#/page/.*#', '', $url1);

Reference