如何通过输入php
中子字符串的第一个和最后一个字符来从字符串中删除子字符串例如在字符串"你好我的名字是John"如果我输入' n'并且' s'它应该返回"你好我的约翰" ...请帮助
答案 0 :(得分:1)
你应该得到第一个和第二个字母的位置,并使用strpos作为方法substr
function my_Cut($string, $first_letter, $second_letter){
$pos[] = strpos($string, $first_letter);
$pos[] = strpos($string, $second_letter);
$result = substr($string, $pos[0] , -($pos[1]-$pos[0]-2));
return str_replace ($result, "", $string);
}
$string = "Hello my name is John";
echo my_Cut($string, "n", "s");
像这样......我想。
答案 1 :(得分:1)
给你的字符串:
$var = "Hello my name is John";
$sub = getSubString($var,"n","s");
echo $sub;
function getSubString($str,$start,$end) {
if(($pos1=strpos($str,$start))===false)
return $str; // not found
if(($pos2=strpos($str,$end,$pos1))===false)
return $str; // not found
return substr($str,0,$pos1).substr($str,$pos2+1);
}
结果:
Hello my John
答案 2 :(得分:1)
/**
* Process function.
* For lack of a better name.
*/
function process($f, $l, $subject)
{
return preg_replace(sprintf('/%s.*?%s/', preg_quote($f), preg_quote($l)), '', $subject);
}
$f = 'n';
$l = 's';
echo process($f, $l, 'Hello my last name is Doe and my first name is John');
输出:
Hello my last Doe at John
我添加了实用程序,但实际上与preg_replace('/n.*?s/', '', $subject)
相同。