我的场景:我尝试在字符串中的主题标签后设置一些名称。
示例:
$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'
)
所以我可以循环访问数组并检查我的数据库中是否存在名字和姓氏。
数据库数据:
| id |名字|姓氏|
| 1 |彼得|格里芬|
| 2 | Stewie |史密斯|
在这个验证之后,我喜欢在字符串中的第一个名字和姓氏旁边放一个div。
谁知道答案?
提前致谢
答案 0 :(得分:1)
您需要使用正则表达式:
//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 ) )
从这里开始,您可以遍历此数组,检查数据库,根据需要进行验证,然后根据结果数据执行任何操作。