好的,标题问题可能听起来令人困惑,是的,我也很困惑。无论如何,我想要的是:假设我有这行文字,
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
将一些逻辑移动到处理函数中。
您可以使用explode 来处理之前有@ 的单词......这真的取决于你想要做什么:
//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;