Reputation: 1239
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
Upvotes: 0
Views: 153
Reputation: 6946
/**
* 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)
.
Upvotes: 1
Reputation: 501
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.
Upvotes: 1
Reputation: 306
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
Upvotes: 1