我想在搜索到的字符串之后总是剪切我的路径:
$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
。
答案 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"