如何在特定字符后剪切字符串?

时间:2016-04-28 09:46:54

标签: php

我想在搜索到的字符串之后总是剪切我的路径:

$subject = "katze/123pferd/123hase/tier/affe/berg";
$search = "affe";

$pos = strpos($subject, $search);
if ($pos !== false) {
    $result = substr($subject, 0, strpos($subject, '/', $pos));
}

echo $result;

这个工作正常,如果我的路径中只有一次元素。

例如案例$search = "affe",结果为katze/123pferd/123hase/tier/affe

对于案例$search = "tier",结果为katze/123pferd/123hase/tier

对于案例$search = "hase",结果为katze/123pferd/123hase

但如果我的案例为$search = "123",则结果为katze/123pferd,但它应为katze/123pferd/123hase

3 个答案:

答案 0 :(得分:2)

试试这个:

  

使用strpos检查最坏的情况。比如123

$subject = "katze/123pferd/123hase/tier/affe/berg";
$search = "affe";

$arr = explode("/", $subject);
$out = array();
foreach($arr as $val){
    $out[] = $val;
    if($val == $search || strpos($val, $search) !== false)
        break;      
}
echo implode("/", $out); //katze/123pferd/123hase/tier/affe

echo '<pre>';
print_r($out);

<强>结果

Array
(
    [0] => katze
    [1] => 123pferd
    [2] => 123hase
    [3] => tier
    [4] => affe
)

答案 1 :(得分:1)

试试这个

<?php

    $subject = "katze/123pferd/123hase/tier/affe/berg";
    $search = "affe";
    echo get_string($subject,$search);

    function get_string($subject,$search){
        $arr = (explode("/",$subject));
        $key = array_search($search, $arr);
        $newrr = array_slice($arr,0,$key+1,true);
        return implode("/",$newrr);
    }

答案 2 :(得分:1)

使用strrpos查找字符串中最后一次出现的子字符串的位置:

$subject = "katze/123pferd/123hase/tier/affe/berg";
$search = "123";

$pos = strrpos($subject, $search);
if ($pos !== false) {
    $result = substr($subject, 0, strpos($subject, '/', $pos));
}

print_r($result);   // "katze/123pferd/123hase"

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