How can I get a single word before or after another word in a given text. For example :
Text = "This is Team One Name"
and what if there is no word but digites before the middle word for example
Text= "This is 100 one Name"
How can I get the 100 ?
How Can I get the word before and after One, being Team and Name? Any regex pattern matching?
By capturing them into group
(?:(?<firstWord>\w+)\s+|^)middleWord(?:\s+(?<secondWord>\w+)|$)
This should do it:
function get_pre_and_post($needle, $haystack, $separator = " ") {
$words = explode($separator, $haystack);
$key = array_search($needle, $words);
if ($key !== false) {
if ($key == 0) {
return $words[1];
}
else if ($key == (count($words) - 1)) {
return $words[$key - 1];
}
else {
return array($words[$key - 1], $words[$key + 1]);
}
}
else {
return false;
}
}
$sentence = "This is Team One Name";
$pre_and_post_array = get_pre_and_post("One", $sentence);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With