正则表达式从PHP中的字符串中获取所有@提到的用户数据
I have below string. This string having data (@[ID:username__FULLNAME]) of three users mentioned. I want to extract them. I have tried below code but not getting desired results.
ID is integer type
username and FULLNAME may contain numbers, letter and all kind of special chars.
$t = 'Hi @[4232:mark__MΛRK ATTLEY] how are you ?
Hi @[4232:ryan__RYΛN вυηту] how are you ?
Hi @[4232:david__DΛVID शाहिद ] how are you ?
';
My PHP CODE:
$pattern = "|(?:(@\[[0-9]+:[\s\S(?!\])]+\]*))|";
preg_match_all($pattern, $string, $mentionList, PREG_PATTERN_ORDER);
print_r($mentionList);
Current Result:
Array
(
[0] => Array
(
[0] => @[4232:mark__MΛRK ATTLEY] how are you ?
Hi @[4232:ryan__RYΛN вυηту] how are you ?
Hi @[4232:david__DΛVID शाहिद] how are you ?
)
[1] => Array
(
[0] => @[4232:mark__MΛRK ATTLEY] how are you ?
Hi @[4232:ryan__RYΛN вυηту] how are you ?
Hi @[4232:david__DΛVID शाहिद] how are you ?
)
)
Expected Result:
Array
(
[0] => Array
(
[0] => @[4232:mark__MΛRK ATTLEY]
[1] => @[4232:ryan__RYΛN вυηту]
[2] => @[4232:david__DΛVID शाहिद ]
)
)
Can someone help me getting the desired results?
Thanks.
我有以下字符串。 此字符串包含三个用户的数据(@ [ID:username__FULLNAME])。 我想提取它们。 我试过下面的代码,但没有得到理想的结果。 p>
ID是整数类型
username,FULLNAME可能包含数字,字母和所有类型的特殊字符。
$ t ='Hi @ [4232:mark__MΛRK ATTLEY]你好吗?
嗨@ [4232:ryan__RYΛNвυηту]你好吗?
嗨@ [4232:david__DΛVIDशाहिद]你好吗?
';
code> pre>
我的PHP代码: p>
$ pattern =“|(?:(@ \ [[0-9] +:[\ s \ S(?!\])] + \] *))|“;
npreg_match_all($ pattern,$ string,$ prompList,PREG_PATTERN_ORDER);
print_r($ desiredList) ;
code> pre>
当前结果: p>
Array
(
[0] => Array
(
[0] => @ [4232:mark__MÎ> RK ATTLEY]你好吗?
嗨@ [4232:ryan__RYγ>Nвυηту]你好吗?
嗨@ [4232:david__Dγ> VIDशाहिद] 你怎么样?
)
[1] =>数组
(
[0] => @ [4232:mark__MÎ> RK ATTLEY]你好吗?
嗨@ [4232 :ryan__RYÎ>Nвυηту]你好吗?
嗨@ [4232:david__Dγ> VIDशाहिद]你好吗?
)
)
code> pre>
预期结果: p>
数组
(
[0] =>数组
(
[0] => @ [4232:mark__MÎ> RK ATTLEY]
[1] => @ [4232:ryan__RYÎ>Nвυηту]
[2] => @ [4232:david__DÎ> VIDश ाहिद]
)
)
code> pre>
有人可以帮助我获得理想的结果吗? p>
谢谢。
div>
You can use this regex with 3 captured groups:
/@\[(\d+):(\S+)\h+(\S+)\h*\]/
RegEx Explanation:
-
@
: Match literal@
-
\[
: Match literal[
-
(\d+)
: Match 1+ digits and capture it in group #1 forid
-
:
: Match literal:
-
(\S+)
: Match 1+ non-whitespace characters and capture it in group #2 forfirstName
-
\h+
: Match 1 or more horizontal whitespaces -
(\S+)
: Match 1+ non-whitespace characters and capture it in group #3 forlastName
-
\h*
: Match 0 or more horizontal whitespaces -
\]
: Match literal]
Not sure if this will give you the exact output you are looking for, but yor regex is a bit too greedy. You can simplify it like this: (?:@\[[0-9]+.+?])
This should return the captured groups separately.
Not sure if the anonymous capture group is needed so it could be simplified down to (@\[[0-9]+.+?])
or possibly even (@\[.+?])
.