子字符串拆分 - PHP
Sub-string splitting - PHP
所以,我想这是一个非常简单的概念,但我不确定如何实现我的预期结果。我想要的是以“@”符号开头的单词,输出时用 <span>
包围它们。
假设下面是整个字符串:
Mark wants the new app to be released on Friday, but some assets need refining so that they fit the theme @design_team.
我将如何捕获...
@design_team
...子字符串,请记住子字符串中不应包含下划线以外的字符,以帮助保持格式。
请让我知道 PHP 是否可行,如果可行,如何实现。
$str = "Mark wants the new app to be released on Friday, but some assets need refining so that they fit the theme @design_team.";
preg_match('/\@[a-zA-Z_]+/', $str, $matches);
print_r($matches);
输出为
Array
(
[0] => @design_team
)
您可以使用正则表达式来实现这一点。这是一个例子:
$string = 'Hello @php and @regex!';
$matches = [];
preg_match_all('/@(\w+)/', $string, $matches);
var_dump($matches);
输出:
array(2) {
[0] =>
array(2) {
[0] =>
string(4) "@php"
[1] =>
string(6) "@regex"
}
[1] =>
array(2) {
[0] =>
string(3) "php"
[1] =>
string(5) "regex"
}
}
延伸阅读:preg_match_all.
使用preg_replace
:
$string = preg_replace('/@\w+/', '<span>[=10=]</span>', $string);
\w
匹配单词字符(字母、数字、下划线),+
匹配它们的序列。并在替换字符串中 [=14=]
获取匹配的子字符串。
我认为使用正则表达式会更容易如果每个字符串有多个@words:
$string = '@Mark wants the new app to be released @Friday, but it needs some @refining';
$didMatch = preg_match_all('/(@[^\W]+)/', $string, $matches);
if($didMatch) {
echo "There were " . count($matches[0]) . " matches: <br />";
print_r($matches[0]);
} else {
echo "No @words in string!\n";
}
所以,我想这是一个非常简单的概念,但我不确定如何实现我的预期结果。我想要的是以“@”符号开头的单词,输出时用 <span>
包围它们。
假设下面是整个字符串:
Mark wants the new app to be released on Friday, but some assets need refining so that they fit the theme @design_team.
我将如何捕获...
@design_team
...子字符串,请记住子字符串中不应包含下划线以外的字符,以帮助保持格式。
请让我知道 PHP 是否可行,如果可行,如何实现。
$str = "Mark wants the new app to be released on Friday, but some assets need refining so that they fit the theme @design_team.";
preg_match('/\@[a-zA-Z_]+/', $str, $matches);
print_r($matches);
输出为
Array
(
[0] => @design_team
)
您可以使用正则表达式来实现这一点。这是一个例子:
$string = 'Hello @php and @regex!';
$matches = [];
preg_match_all('/@(\w+)/', $string, $matches);
var_dump($matches);
输出:
array(2) {
[0] =>
array(2) {
[0] =>
string(4) "@php"
[1] =>
string(6) "@regex"
}
[1] =>
array(2) {
[0] =>
string(3) "php"
[1] =>
string(5) "regex"
}
}
延伸阅读:preg_match_all.
使用preg_replace
:
$string = preg_replace('/@\w+/', '<span>[=10=]</span>', $string);
\w
匹配单词字符(字母、数字、下划线),+
匹配它们的序列。并在替换字符串中 [=14=]
获取匹配的子字符串。
我认为使用正则表达式会更容易如果每个字符串有多个@words:
$string = '@Mark wants the new app to be released @Friday, but it needs some @refining';
$didMatch = preg_match_all('/(@[^\W]+)/', $string, $matches);
if($didMatch) {
echo "There were " . count($matches[0]) . " matches: <br />";
print_r($matches[0]);
} else {
echo "No @words in string!\n";
}