如何在一行文本中选择多个文本,@作为文本的第一个字母


How to select multiple texts with @ as the first letter of the text inside a line of texts?

好吧,标题问题可能听起来令人困惑,是的,我也感到困惑。无论如何,我想要的是这个:假设我有这一行文字,

The quick brown @fox jumps @over the @lazy dog.
这行文本

是从数据库中动态获取的"单行",而不是文本数组。假设首字母为"@"的文本是指向页面或其他内容的链接,我希望我可以指定放置锚标签的位置,就我而言,我想在每个文本上放置锚标签以"@"开头。

我尝试过爆炸,但似乎爆炸不是这个问题的答案。有人可以在这里帮助我吗?谢谢。

您不想为此使用explode,而是正则表达式。为了匹配多次出现,preg_match_all是交易。

preg_match_all('/@'w+/', $input, $matches);
        #        @   is the literal "@" character
        #    and 'w+ matches consecutive letters

您当然可能希望使用preg_replace将它们转换为链接。或者更好的preg_replace_callback将一些逻辑移动到处理程序函数中。

您可以使用爆炸来处理之前有 @ 的单词... 这实际上取决于您要做什么:

//Store the string in a variable
$textVar = "The quick brown @fox jumps @over the @lazy dog.";
//Use explode to separate words
$words = explode(" ", $textVar);
//Check all the variables in the array, if the first character is a @
//keep it, else, unset it
foreach($words as $key=>$val) {
    if(substr($val, 0, 1) != "@") {
        unset($words[$key]);
    } else {
        $words[$key] = "<a href='#'>".$words[$key]."</a>";
    }
}
//You can now printout the array and you will get only the words that start with @
foreach($words as $word) {
    echo $word."<br>";
}

您还可以保留没有 @ 的字符串,并使用内爆将所有内容放在一起:

//Store the string in a variable
$textVar = "The quick brown @fox jumps @over the @lazy dog.";
//Use explode to separate words
$words = explode(" ", $textVar);
//Check all the variables in the array, if the first character is a @
//keep it, else, unset it
foreach($words as $key=>$val) {
    if(substr($val, 0, 1) != "@") {
        //Do nothing
    } else {
        $words[$key] = "<a href='#'>".$words[$key]."</a>";
    }
}
//You can now printout the string
$words = implode($words, " ");
echo $words;