How can i remove substring from string by entering first and last character of substring in php
For example in string "Hello my name is John" if i enter 'n' and 's' it should return "Hello my John"... Please Help
/**
* 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');
Output:
Hello my last Doe at John
I added utility, but it is effectively the same as preg_replace('/n.*?s/', '', $subject).
with your string given:
$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);
}
results in:
Hello my John
strpos has an offset parameter that should probably be used (in case second character is present before first ("sHello my name is John" would fail in your example).You should get the position of the first and second letter and use strpos for the method 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");
Something like this... I think.
strpos should be used with $offset parameter to avoid instances where $second_letter occurs before $first_letter.
strposoversubstr?Hello my last name is Doe and my first name is John. And what if only one of the two letters appear in the string?