在主题标签后设置字符串中的特定字词样式 - php

Style specific words in string after hashtag - php

我的情况:我尝试在字符串中的主题标签后设置一些名称的样式。

示例:

$string = 'Lorem #Stewie Smith ipsum dolor #Peter Griffin sit amet, consectetuer #Stewie Griffin.';

首先,我想将这些名称放在一个数组中,例如:

array(

    [item 1]
    [firstname] => 'Peter'
    [surname] => 'Griffin'

    [item 2]
    [firstname] => 'Stewie'
    [surname] => 'Griffin'

    [item 3]
    [firstname] => 'Stewie'
    [surname] => 'Smith'

)

所以我可以遍历数组并检查我的数据库中是否存在名字和姓氏。

数据库数据:

|编号 |名字 |姓氏 |

| 1 |彼得 |格里芬 |

| 2 |史威 |史密斯 |

在验证之后,我想在字符串中的名字和姓氏周围放置一个 div。

谁知道答案?

提前致谢

您需要使用正则表达式:

//Regular expression (explained below)
$re = "/\#([a-zA-Z]*)\s([a-zA-Z]*)/"; 

//String to search
$str = "Lorem #Stewie Smith ipsum dolor #Peter Griffin sit amet, consectetuer #Stewie Griffin."; 

//Get all matches into $matches variable
preg_match_all($re, $str, $matches);

$matches 现在是:

Array
(
    [0] => Array
        (
            [0] => #Stewie Smith
            [1] => #Peter Griffin
            [2] => #Stewie Griffin
        )

    [1] => Array
        (
            [0] => Stewie
            [1] => Peter
            [2] => Stewie
        )

    [2] => Array
        (
            [0] => Smith
            [1] => Griffin
            [2] => Griffin
        )

)

因此每个名称都包含并可通过以下方式访问:

$matches[0][n] //full match
$matches[1][n] //first name
$matches[2][n] //last name

放入数组中:

$names = [];

foreach($matches[0] as $i => $v){
    $names[] = array("firstname" => $matches[1][$i], "lastname" => $matches[2][$i]);
}

现在 $names 是:

Array
(
    [0] => Array
        (
            [firstname] => Stewie
            [lastname] => Smith
        )

    [1] => Array
        (
            [firstname] => Peter
            [lastname] => Griffin
        )

    [2] => Array
        (
            [firstname] => Stewie
            [lastname] => Griffin
        )

)

从这里开始,您可以遍历此数组,检查您的数据库,根据您的需要进行验证,然后对结果数据执行任何操作。