这是我的字符串:
monkey/rabbit/cat/donkey/duck
如果我的变量cat
...
$animal = cat
。我想删除cat
之后的所有内容。
我想要的结果是:
monkey/rabbit/cat
我尝试使用str_replace
:
$subject = 'monkey/rabbit/cat/donkey/duck';
$trimmed = str_replace($animal, '', $subject);
echo $trimmed;
但在这里我得到了结果:
monkey/rabbit//donkey/duck
所以它只是削减cat
.
您可以将 strpos 与 substr 组合:
$pos = strpos($subject, $animal);
if ($pos !== false) {
$result = substr($subject, 0, $pos + strlen($animal));
}
如果要确保仅擦除整个段,在部分匹配的情况下,可以使用 offset 参数 strpos
:
$pos = strpos($subject, $animal);
if ($pos !== false) {
$result = substr($subject, 0, strpos($subject, '/', $pos));
}
您可以在您的情况下使用 explode
:
$string = "monkey/rabbit/cat/donkey/duck";
$val = explode("donkey", $string );
echo $val[0];
Result: monkey/rabbit/cat
PS* 当然有更好的方法来做到这一点
我的方法是通过您的变量explode
。
取第一部分并附加变量。
<?php
$string = 'monkey/rabbit/cat/donkey/duck';
$animal = 'cat';
$temp = explode($animal,$string);
print $temp[0] . $animal;
将很好地输出
monkey/rabbit/cat
无需使用任何strpos
、strlen
、substr
或donkeys
<?php
$animal="cat";
$string1="monkey/rabbit/cat/donkey/duck";
$parts = explode($animal, $string1);
$res = $parts[0];
print("$res$animal")
?>
以下是对每个步骤的作用的一些解释:
$subject = 'monkey/rabbit/cat/donkey/duck';
$target = 'cat';
$target_length = strlen($target); // get the length of your target string
$target_index = strpos($subject, $target); // find the position of your target string
$new_length = $target_index + $target_length; // find the length of the new string
$new_subject = substr($subject, 0, $new_length); // trim to the new length using substr
echo $new_subject;
这一切都可以组合成一个语句。
$new_subject = substr($subject, 0, strpos($subject, $target) + strlen($target));
这假设您的目标已找到。如果找不到目标,主题将被修剪到目标的长度,这显然不是你想要的。例如,如果目标字符串"fish"
则新主题将为 "monk"
。这就是为什么另一个答案检查if ($pos !== false) {
。
关于你的问题的评论之一提出了一个有效的观点。如果搜索恰好包含在其他字符串之一中的字符串,则可能会得到意外结果。使用substr
/strpos
方法时,确实没有避免此问题的好方法。如果要确保在分隔符(/
)之间仅匹配完整的单词,则可以按/
分解并在生成的数组中搜索目标。
$subject = explode('/', $subject); // convert to array
$index = array_search($target, $subject); // find the target
if ($index !== false) { // if it is found,
$subject = array_slice($subject, 0, $index + 1); // remove the end of the array after it
}
$new_subject = implode('/', $subject); // convert back to string
我可能会因为走正则表达式路线而大吃一惊,但是......
$subject = 'monkey/rabbit/polecat/cat/catfish/duck';
$animal = "cat";
echo preg_replace('~(.*(?:/|^)' . preg_quote($animal) . ')(?:/|$).*~i', "$1", $subject);
这将确保您的动物立即用/
字符包裹在两侧,或者它位于字符串的开头或结尾(即猴子或鸭子)。
所以在这个例子中,它将输出:
monkey/rabbit/polecat/cat
以猫结束,而不是绊倒在polecat或鲶鱼身上