简体   繁体   中英

Get string from a specif word to another word even if these words are more than once in a string

With a string like this one:

$sentence='StartDetails text 1 EndDetails StartDetails text 2 EndDetails  StartDetails text 3 EndDetails StartDetails text 4 EndDetails';

How can I get the text between StartDetails and EndDetails words even if they appear n numbers of times on string?

Regular expressions should help, try this:

$sentence='StartDetails text 1 EndDetails StartDetails text 2 EndDetails  StartDetails text 3 EndDetails StartDetails text 4 EndDetails';

preg_match_all('/StartDetails(.*)EndDetails/U', $sentence, $outputArray);

print_r($outputArray);

In the $outputArray , the second element should be an array of all possible texts between StartDetails and EndDetails.

The key things to note here are the use of the U modifier, that makes the match greedy and the preg_match_all function instead of just preg_match which matches all occurrences

EDIT

Since we don't need to match StartDetails or EndDetails I have changed this

preg_match_all('/(StartDetails)(.*)(EndDetails)/U', $sentence, $outputArray);

to

preg_match_all('/StartDetails(.*)EndDetails/U', $sentence, $outputArray);

Assuming your String has always the same structure: Using explode() within a loop is a possible option:

$sentence='StartDetails text 1 EndDetails StartDetails text 2 EndDetails  StartDetails text 3 EndDetails StartDetails text 4 EndDetails';

$a = explode("StartDetails", $sentence);

foreach($a as $k=>$v){
    if(!empty($v)){
        $b[] = explode( "EndDetails", $v)[0];
    }
}

print_r($b);

// output
Array
(
    [0] =>  text 1 
    [1] =>  text 2 
    [2] =>  text 3 
    [3] =>  text 4 
)

Try this regex (?<=StartDetails\\s).*?(?=\\s+EndDetails) . It matches everything between StartDetails and EndDetails . The regex uses Lookahead and Lookbehind pattern to match more than one value.

Then use preg_match_all in PHP.

You can use array_walk , explode

$senteanceToArray = array_filter(explode('StartDetails',$sentence));
array_walk($senteanceToArray, function(&$v, $k){
 return $v = trim(str_replace('EndDetails', '', $v));
});
echo '<pre>';
print_r($senteanceToArray);

You can use also str_replace

$sentence='StartDetails text 1 EndDetails StartDetails text 2 EndDetails  StartDetails text 3 EndDetails StartDetails text 4 EndDetails';
$patterns = ['StartDetails','EndDetails'];
$replacements = ['','#'];
$words = array_map('trim', array_filter(explode("#",str_replace($patterns, $replacements, $sentence))));

Result :-

Array
(
 [0] => text 1
 [1] => text 2
 [2] => text 3
 [3] => text 4
)

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