所以,我想这是一个非常简单的概念,但我不确定如何实现我的预期结果。我想要的是用'@'符号开头的文字,用包含它们的<span>
输出。子字符串拆分 - PHP
比方说,下面是整个字符串:
马克希望新的应用程序上周五发布,但一些资产需要细化,使它们贴合主题@design_team。
我将如何捕捉...
@design_team
...子串,铭记不是下划线其他字符不应该被占子字符串,以帮助保持格式。
请让我知道这是否可能与PHP,如果是这样,如何。
所以,我想这是一个非常简单的概念,但我不确定如何实现我的预期结果。我想要的是用'@'符号开头的文字,用包含它们的<span>
输出。子字符串拆分 - PHP
比方说,下面是整个字符串:
马克希望新的应用程序上周五发布,但一些资产需要细化,使它们贴合主题@design_team。
我将如何捕捉...
@design_team
...子串,铭记不是下划线其他字符不应该被占子字符串,以帮助保持格式。
请让我知道这是否可能与PHP,如果是这样,如何。
使用preg_replace
:
$string = preg_replace('/@\w+/', '<span>$0</span>', $string);
\w
匹配单词字符(字母,数字,下划线),+
使得它们匹配的序列。并在替换字符串$0
获取匹配的子字符串。
完美,谢谢Barmar! –
$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
)
我知道这会打印出@design_team子字符串,但是我如何将它作为字符串本身的一部分进行打印,以便它的格式为:
Mark要...符合主题 @ design_team。
–没关系,Barmar已经回答了这个解决方案。不管怎样,谢谢你。 –
您可以使用正则表达式来实现这一目标。这里有一个例子:
$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。
我认为这将是更容易,如果你有每串多个@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";
}
你需要使用正则表达式和编写模式匹配'前缀任何workd @ ' –