I’m working on a simple mention system and in my PHP script and I need to extract client:6
from the larger text where one or more @mention like @[John Doe (#6)](client:6)
will be present.
Ex. This is my text how do you like it @John and do you have any thoughts @Jane
In php the string will look like.
JavaScript
x
This is my text how do you like it @[John Doe (#6)](client:6) and do you have any thoughts @[Jane Doe (#7)](client:7)
and i need to get an array with array('client:6','client:7')
Advertisement
Answer
One of many possible ways would be
JavaScript
@[[^][]+]s*(K[^()]+
In terms of regular expressions, this boils down to
JavaScript
@ # "@" literally
[ # "[" literally
[^][]+ # not "[" nor "]" as many times as possible
]s* # followed by "]" literally + whitespaces, eventually
( # you name it - "(" literally
K # forget all what has been matched that far
[^()]+ # not "(" nor ")"
In PHP
this could be
JavaScript
<?php
$data = "This is my text how do you like it @[John Doe (#6)](client:6) and do you have any thoughts @[Jane Doe (#7)](client:7)";
$regex = "~@[[^][]+]s*(K[^()]+~";
preg_match_all($regex, $data, $matches);
print_r($matches);
?>
And would yield
JavaScript
Array
(
[0] => Array
(
[0] => client:6
[1] => client:7
)
)
See a demo on ideone.com.