如何在最后一个破折号后删除字符串

时间:2015-04-30 09:54:04

标签: php regex

我想要删除一个已知的字符串(实际上是其中四个),例如。一,二,三或四。

或相同的效果是在最后一个斜线

之后删除字符串

我爆炸了网址以获取字符串但我只想保留字符串直到最后一个短划线。 例如url http://www.website.com/page/nameIwantTokeep-RemoveThis/product/ 我想删除实际页面上的RemoveThis

    $path = $_SERVER['REQUEST_URI'];
    $build = strpos($path, 'back')||
             strpos($path, 'front');

    if ($build > 0) {

    $array = explode('/',$path);

    $slice = (array_slice($array, 2, 1));  

    foreach($slice as $key => $location);

3 个答案:

答案 0 :(得分:3)

使用正则表达式:

使用此正则表达式进行搜索:

-[^/-]+(?![^-]*-)

用空字符串替换。

<强>代码:

$re = "~-[^/-]+(?![^-]*-)~"; 
$str = "http://www.website.com/page/name-IwantTokeep-RemoveThis/product/"; 

$result = preg_replace($re, "", $str, 1);

RegEx Demo

答案 1 :(得分:2)

我知道你的问题是关于正则表达式,但我真的不需要它。 您应该考虑使用strrpos来查找字符串中最后一个破折号的索引,并获取所需的子字符串(substr)。

$input = "whatever-removethis";
$index = strrpos($input, "-");
if(index === false) //in case no dash was found
{
    $output = $input;
}
else
{
    $output = substr($input, 0, $index);
}

http://php.net/manual/en/function.strrpos.php

http://php.net/manual/en/function.substr.php

答案 2 :(得分:0)

您可以使用以下内容进行匹配:

(-(?!.*-)[^\/]*)

并替换为''(空字符串)

请参阅DEMO

相关问题