简体   繁体   中英

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?

将它们捕获到组中

(?:(?<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);
<?php
$Text = "This is Team One Name";
$Word = 'Team';
preg_match('#([^ ]+\s+)' . preg_quote($Word) . '(\s[^ ]+)#i', $Text, $Match);
print_r($Match);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM