Duncan McClean
Duncan McClean

Reputation: 192

How can I get the word after a string?

I have a string which somewhere contains Style Name: Something. What I want to be able to do is search for Style Name: and get back Something or whatever that value is.

I know I need to do something with strpos to search the string but I'm pretty much stuck on getting the value.

Upvotes: 0

Views: 51

Answers (4)

The fourth bird
The fourth bird

Reputation: 163207

Another option is to make use of \K to forget what was matched and match 0+ times a horizontal whitespace \h*:

\bStyle Name:\h*\K\S+

Regex demo | Php demo

$re = '/\bStyle Name:\h*\K\S+/m';
$str = 'Style Name: Something Style Name: Something Style Name: Something';
preg_match_all($re, $str, $matches);
print_r($matches[0]);

Result

Array
(
    [0] => Something
    [1] => Something
    [2] => Something
)

Upvotes: 0

Andreas
Andreas

Reputation: 23958

You don't need regex.
Two simple explodes and you got the style name.

$str = "something something Style Name: Something some more text";

$style_name = explode(" ",explode("Style Name: ", $str)[1])[0];

echo $style_name; // Something

Upvotes: 1

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

With positive lookbehind,

<?php
$string="Style Name: Something with colorful";
preg_match('/(?<=Style Name: )\S+/i', $string, $match);
echo $match[0];
?>

DEMO: https://3v4l.org/OICqF

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520908

You could use preg_match_all:

$input = "Sample text Style Name: cats and also this Style Name: dogs";
preg_match_all("/\bStyle Name:\s+(\S+)/", $input, $matches);
print_r($matches[1]);

This prints:

Array
(
    [0] => cats
    [1] => dogs
)

The pattern used \bStyle Name:\s+(\S+) matches Style Name: followed by one or more spaces. Then, it matches and captures the next word which follows.

Upvotes: 1

Related Questions