Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a single word before or after another word

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?

like image 426
Faouzi FJTech Avatar asked Dec 12 '25 21:12

Faouzi FJTech


2 Answers

By capturing them into group

(?:(?<firstWord>\w+)\s+|^)middleWord(?:\s+(?<secondWord>\w+)|$)
like image 90
Anirudha Avatar answered Dec 15 '25 14:12

Anirudha


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);
like image 36
n1te Avatar answered Dec 15 '25 14:12

n1te



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!