Sarabveer
Sarabveer

Reputation: 29

How to get the first word before a separator in PHP

So Basically I have a string like this:

kbIr cugY icqwrY BI; cugY cuig cuig icqwry ]

What can I do so PHP takes part of the string before ; and then gets the first word before the separator so the output would be:

BI

So far I have: strtok($g, ';');, but that only gets the first half of the string before the separator, not the first word before the separator.

Upvotes: 0

Views: 98

Answers (3)

Oliver
Oliver

Reputation: 893

Just to be complete and if you don't like regex:

$value = end(explode(" ", array_shift(explode(";", "kbIr cugY icqwrY BI; cugY cuig cuig icqwry ]"))));

print_r($value); // prints BI

Upvotes: 2

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

To get only the first word before the separator it's enough to use preg_match function:

$str = 'kbIr cugY icqwrY BI; cugY cuig cuig icqwry ]';
preg_match("/\b\w+(?=;)/i", $str, $m);

print_r($m[0]);

The output:

BI

Upvotes: 1

OptimusCrime
OptimusCrime

Reputation: 14863

This regex pattern matches upper and lowercased letters (with no space) followed by a semicolon. I've also added a named group for the capture.

(?P<sep>[a-zA-Z]*);

Example use

$re = '/(?P<sep>[a-zA-Z]*);/';
$str = 'kbIr cugY icqwrY BI; cugY cuig cuig icqwry ]';

preg_match_all($re, $str, $matches);

// Print the entire match result
print_r($matches);

Outputs

Array
(
    [0] => Array
        (
            [0] => BI;
        )

    [sep] => Array
        (
            [0] => BI
        )

    [1] => Array
        (
            [0] => BI
        )
)

Simplified

if (isset($matches['sep']) and len($matches['sep']) > 0) {
    echo $matches['sep'][0]; // BI
}

Upvotes: 3

Related Questions