如何用@作为文本行内文本的第一个字母来选择多个文本?

时间:2012-07-02 18:39:12

标签: php explode

好的,标题问题可能听起来令人困惑,是的,我也很困惑。无论如何,我想要的是这样的: 说我有这行文字,

The quick brown @fox jumps @over the @lazy dog.

这行文本是从数据库中动态获取的“单行”,而不是文本数组。假设第一个字母为“@”的文本是指向某个页面的链接,我希望我可以指定放置锚标记的位置,在我的情况下,我想在每个文本上添加锚标记,以' @”。

我试过爆炸,但似乎爆炸不是解决这个问题的答案。有人可以帮帮我吗?感谢。

2 个答案:

答案 0 :(得分:2)

您不希望使用explode,而是使用正则表达式。为了匹配多个出现,preg_match_all就是合约。

preg_match_all('/@\w+/', $input, $matches);

        #        @   is the literal "@" character
        #    and \w+ matches consecutive letters

您确定可能希望使用preg_replace将其转换为链接。或者更好的是preg_replace_callback将一些逻辑移动到处理函数中。

答案 1 :(得分:0)

你可以使用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;