我怎样才能得到字符串后面的单词?
How can I get the word after a string?
我有一个字符串,其中某处包含 Style Name: Something
。我想要做的是搜索 Style Name:
并返回 Something
或任何值。
我知道我需要用 strpos
做一些事情来搜索字符串,但我几乎无法获取值。
您可以使用 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]);
这会打印:
Array
(
[0] => cats
[1] => dogs
)
使用的模式 \bStyle Name:\s+(\S+)
匹配 Style Name:
后跟一个或多个空格。然后,它匹配并捕获后面的下一个单词。
积极回顾,
<?php
$string="Style Name: Something with colorful";
preg_match('/(?<=Style Name: )\S+/i', $string, $match);
echo $match[0];
?>
你不需要正则表达式。
两个简单的爆炸,你就得到了样式名称。
$str = "something something Style Name: Something some more text";
$style_name = explode(" ",explode("Style Name: ", $str)[1])[0];
echo $style_name; // Something
另一种选择是利用\K
忘记匹配的内容并匹配0+次水平空白\h*
:
\bStyle Name:\h*\K\S+
$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]);
结果
Array
(
[0] => Something
[1] => Something
[2] => Something
)
我有一个字符串,其中某处包含 Style Name: Something
。我想要做的是搜索 Style Name:
并返回 Something
或任何值。
我知道我需要用 strpos
做一些事情来搜索字符串,但我几乎无法获取值。
您可以使用 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]);
这会打印:
Array
(
[0] => cats
[1] => dogs
)
使用的模式 \bStyle Name:\s+(\S+)
匹配 Style Name:
后跟一个或多个空格。然后,它匹配并捕获后面的下一个单词。
积极回顾,
<?php
$string="Style Name: Something with colorful";
preg_match('/(?<=Style Name: )\S+/i', $string, $match);
echo $match[0];
?>
你不需要正则表达式。
两个简单的爆炸,你就得到了样式名称。
$str = "something something Style Name: Something some more text";
$style_name = explode(" ",explode("Style Name: ", $str)[1])[0];
echo $style_name; // Something
另一种选择是利用\K
忘记匹配的内容并匹配0+次水平空白\h*
:
\bStyle Name:\h*\K\S+
$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]);
结果
Array
(
[0] => Something
[1] => Something
[2] => Something
)