使用preg_replace和str_ireplace

时间:2015-05-05 17:21:40

标签: php preg-replace str-replace

这是我当前代码的副本:

<?
function smarty_modifier_url(&$url) {

    //remove html tags
    $url = strip_tags($url);

    trim($url);
    $url = preg_replace ( '%[.,:\'"/\\\\[\]{}\%\-_!?]%simx', ' ', $url );
    $url = str_ireplace ( " ", "-", $url );
    return $url;
}
?>

此代码正在修改我网站上显示的网址。这是其中一个网址的副本:

http://example.com/listing/1/Testing-|-See-If-This-Works-

我需要更改上述代码才能删除|以显示在网址中并删除网址末尾的-?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

这样做:

$url = preg_replace('/(\||-$)/', '', $url );

示例:

<?
function smarty_modifier_url(&$url) {

    //remove html tags
    $url = strip_tags($url);

    trim($url);
    $url = preg_replace ( '%[.,:\'"/\\\\[\]{}\%\-_!?]%simx', ' ', $url );
    $url = str_replace ( " ", "-", $url );
    $url = preg_replace('/(\||-$)/', '', $url );
    $url = preg_replace('/[-]{2,}/', '-', $url);
    return $url;
}
?>

演示:

http://ideone.com/XEIvFt

正则表达式解释:

(\||-$)


Match the regex below and capture its match into backreference number 1 «(\||-$)»
   Match this alternative «\|»
      Match the character “|” literally «\|»
   Or match this alternative «-$»
      Match the character “-” literally «-»
      Assert position at the end of the string, or before the line break at the end of the string, if any «$»