Reputation: 532
Im using a mentioning system like on twitter and instagram where you simply put @johndoe
what im trying to do is be able to strip down to the name in-between "@" and these characters ?
,,
,]
,:
,(space)
as an example heres my string:
hey @johnDoe check out this event, be sure to bring @janeDoe:,@johnnyappleSeed?, @johnCitizen] , and @fredNerk
how can i get an array of janeDoe
,johnnyappleSeed
,johnCitizen
,fredNerk
without the characters ?
,,
,]
,:
attached to them.
i know i have to use a variation of preg_match
but i dont have a strong understanding of it.
Upvotes: 0
Views: 181
Reputation: 91373
How about:
$str = 'hey @johnDoe check out this event, be sure to bring @janeDoe:,@johnnyappleSeed?, @johnCitizen] , and @fredNerk';
preg_match_all('/@(.*?)(?:[?, \]: ]|$)/', $str, $m);
print_r($m);
output:
Array
(
[0] => Array
(
[0] => @johnDoe
[1] => @janeDoe:
[2] => @johnnyappleSeed?
[3] => @johnCitizen]
[4] => @fredNerk
)
[1] => Array
(
[0] => johnDoe
[1] => janeDoe
[2] => johnnyappleSeed
[3] => johnCitizen
[4] => fredNerk
)
)
explanation:
The regular expression:
(?-imsx:@(.*?)(?:[?, \]: ]|$))
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
@ '@'
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
.*? any character except \n (0 or more times
(matching the least amount possible))
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
(?: group, but do not capture:
----------------------------------------------------------------------
[?, \]: ] any character of: '?', ',', ' ', '\]',
':', ' '
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
$ before an optional \n, and the end of
the string
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
Upvotes: 0
Reputation: 21
$check_hash = preg_match_all ("/@[a-zA-Z0-9]*/g", $string_to_match_against, $matches);
You could then do somthing like
foreach ($matches as $images){
echo $images."<br />";
}
UPDATE: Just realized you were looking to remove the invalid characters. Updated script should do it.
Upvotes: 0
Reputation: 16061
This is what you've asked for: /\@(.*?)\s/
This is what you really want: /\b\@(.*?)\b/
Put either one into preg_match_all()
and evaluate the results array.
Upvotes: 1