如何从字符串链接部分后删除任何字符?

时间:2015-12-12 01:18:49

标签: php string

我试试这样:

$string = "localhost/product/-/123456-Ebook-Guitar";
echo $string = substr($string, 0, strpos(strrev($string), "-/(0-9+)")-13);

和输出工作:

localhost/product/-/123456 cause this just for above link with 13 character after /-/123456

如何删除所有?我试试

$string = "localhost/product/-/123456-Ebook-Guitar";
echo $string = substr($string, 0, strpos(strrev($string), "-/(0-9+)")-(.*));

不工作和错误sintax。

我试试

$string = "localhost/product/-/123456-Ebook-Guitar";
echo $string = substr($string, 0, strpos(strrev($string), "-/(0-9+)")-999);

输出为空..

2 个答案:

答案 0 :(得分:1)

不是单行,但这可以解决问题:

$string = "localhost/product/-/123456-Ebook-Guitar";

// explode by "/"
$array1 = explode('/', $string);

// take the last element
$last = array_pop($array1);

// explode by "-"
$array2 = explode('-', $last);

// and finally, concatenate only what we want
$result = implode('/', $array1) . '/' . $array2[0];

// $result ---> "localhost/product/-/123456"

答案 1 :(得分:1)

假设在localhost/product/-/123456之后没有数字,那么我将用下面的

修剪它
$string = "localhost/product/-/123456-Ebook-Guitar";
echo rtrim($string, "a..zA..Z-"); // localhost/product/-/123456

另一个非正则表达式版本,但需要5.3.0 +

$str = "localhost/product/-/123456-Ebook-Guitar-1-pdf/";
echo dirname($str) . "/" . strstr(basename($str), "-", true); //localhost/product/-/123456

这是一种更灵活的方式,但涉及正则表达式

$string = "localhost/product/-/123456-Ebook-Guitar";

echo preg_replace("/^([^?]*-\/\d+)([^?]*)/", "$1", $string);
// localhost/product/-/123456

$string = "localhost/product/-/123456-Ebook-Guitar-1-pdf/";
echo preg_replace("/^([^?]*-\/\d+)([^?]*)/", "$1", $string); 
// localhost/product/-/123456

这应该匹配捕获的所有内容,然后删除所有内容

regex101: localhost/product/-/123456-Ebook-Guitar

regex101: localhost/product/-/123456-Ebook-Guitar-1-pdf/