regex find usernames starting with # php - php

so i want to find usernames in a string and put them in an array, i've made the regex and it returns the match, but when there are 2 matches it only puts the first one in the array. Can anyone see what is wrong with my regex?
$reactie = 'hey #sjerd and #jeska';
$pattern = '/#\w*/';
preg_match($pattern, $reactie, $matches);
print_r($matches);

You need to use preg_match_all with correct regex with word boundary:
$reactie = 'hey #sjerd and #jeska';
$pattern = '/#\w+\b/';
preg_match_all($pattern, $reactie, $matches);
print_r($matches[0]);

Related

regex to get name from the string in php

I have no idea how to make a regex , that's why i am asking this question.I have one string like chirag patel <chiragxxx#gmail.com>
I have a regex to get email id from the string.
preg_match("/\<(.*)\>/", $data['From'], $matches);
$email = $matches[1];
How to get name from above string using regex?
my expected output is: chirag patel.
You can use the regex
.*(?=\<(.*)\>)
check the demo here. here is the php code for the following
$re = '/.*(?=\<(.*)\>)/';
$str = 'chirag patel <chiragxxx#gmail.com>';
preg_match($re, $str, $matches);
var_dump($matches[0]);
Use this in php
$data['From'] = "chirag patel <chiragxxx#gmail.com>";
preg_match("/.*(?=\<(.*)\>)/", $data['From'], $matches);
print_r($matches); // 0 : name, 1 : email
You add a capturing group for the name.
preg_match("/(.*)\<(.*)\>/", $data['From'], $matches);
$name = $matches[1];
$email = $matches[2];
You may use this regex to capture name and email address in 2 separate groups:
(\pL+[\pL\h.-]*?)\h*<([^>]+)>
RegEx Demo
RegEx Breakup:
(\pL+[\pL\h.-]*?) # group #1 that match 1+ name consisting Unicode letters, dots, hyphens, spaces
\h*: Match 0 or more whitespaces
<([^>]+)>: group #2 to capture email address between < and > characters
Code:
preg_match('~(\pL+(?:[\pL\h-]*\pL)?)\h*<([^>]+)>~u', $str, $matches);
// Print the entire match result
print_r($matches);
I know it has been answered but because it's in PHP, which supports named patterns, and because might look cool:
/(?<name>.*?) \<(?<email>.*?)\>/g
name and email will be keys in the $matches array.

Perform word match in a String until another word is found in the String

I'm using preg_match_all to perform all match in a String
$match_this = '/cola/';
$sentence = 'cola this cola is a nice cola';
if(preg_match_all($match_this, $sentence, $matches)){
echo 'match found'.'<br>';
print_r($matches[0]);
}
But I want this match performing operation to stop when I encounter the word nice and $matches array shouldn't store any more matched word after that.
How the code can be modified for this ?
There can be multiple times 'cola' comes before 'nice'. This is just
an example sentence. Again 'cola' and 'nice' are just example words.
The words to match and where to stop are randomly picked from
database. This code is for a word game.
You could use positive lookahead:
$match_this = '\bcola\d\b';
$until = '\bnice\b';
$sentence = 'cola1 this cola2 is a nice cola3';
if(preg_match_all("/$match_this(?=.*$until)/", $sentence, $matches)){
print_r($matches[0]);
}
Output:
Array
(
[0] => cola1
[1] => cola2
)
I've added a number at the end of each cola to be sure it matches only the ones that are before the word nice.
I've also added word boudaries arround the words to match.
Finally the code is:
$match_this = '\bcola\b';
$until = '\bnice\b';
$sentence = 'cola this cola is a nice cola';
if(preg_match_all("/$match_this(?=.*$until)/", $sentence, $matches)){
print_r($matches[0]);
}
First get the offset of nice, then run the preg match on the substring before it.
$sentence = 'cola this cola is a nice cola';
$match_this = '/nice/';
if(preg_match($match_this, $sentence, $matches, PREG_OFFSET_CAPTURE)){
$niceOffset = $matches[0][1];
$match_this = '/cola/';
if(preg_match_all($match_this, substr($sentence, 0, $niceOffset), $matches2, PREG_OFFSET_CAPTURE)){
var_dump($matches2);
}
}

Using regex in php to find string values between characters multiple times

Here I have a string, "Hello World! I am trying out regex in PHP!". What I want to do is retrieve string values between a set of characters. In this example, the characters are ** **
$str = "**Hello World!** I am trying out regex in PHP!";
preg_match('#\*\*(.*)\*\*#Us', $str, $match);
echo $match[1];
This will echo out "Hello World!", but I want to echo out several matches:
$str = "**Hello World!** I am trying out **regex in PHP!**";
How would I be able to do so? I tried using preg_match_all() but I don't think I was using it properly, or that it would work at all in this case.
You can use:
$str = "**Hello World!** I am trying out **regex in PHP!**";
preg_match_all('/\*{2}([^*]*)\*{2}/', $str, $m);
print_r($m[1]);
Array
(
[0] => Hello World!
[1] => regex in PHP!
)
Even your regex #\*\*(.*)\*\*#Us should work with this but my suggested regex is little more efficient due to negation based pattern [^*]*
You got 1 match owing to using preg_match.You should use preg_match_all Here is another pattern.It uses word non word match between the delimiters
<?php
$str = "**Hello World!** I am trying out **regex in PHP!**";
$regex='/\*\*([\w\W]*)\*\*/iU';
preg_match_all($regex, $str, $m);
print_r($m[1]);
I suggest you to use a non-greedy form of regex. Because i think you want to match also the contents (text inside **) where the single * resides.
$str = "**Hello World!** I am trying out **regex in PHP!**";
preg_match_all('~\*\*(.*?)\*\*~', $str, $matches);
print_r($matches[1]);
DEMO

How to get word in php which contains colon(:)?

I have a word Hello How are you :chinu i am :good i want to get the word which contains : like :chinu and :good
My code:
<?php
//$string='Hello How are you :chinu i am :good';
//echo strtok($string, ':');
$string='Hello How are you :chinu i am :good';
preg_match('/:([:^]*)/', $string, $matches);
print_r($matches);
?>
Above code i am getting Array ( [0] => : [1] => ) But not getting the exact text. Please help me.
Thanks
Chinu
To get all matches you need to use preg_match_all(). As far as your regular expression goes your negated class is backwards; matching any character of: :, ^ "zero or more" times and will not match what you expect.
You stated in the comments about the "records" being printed twice, this is because you print the $matches array itself instead of printing the group index which only displays the match results.
preg_match_all('/:\S+/', $string, $matches);
print_r($matches[0]);
:\S+
Try this.See demo.
http://regex101.com/r/tF5fT5/43
$re = "/:\\S+/im";
$str = "Hello How are you :chinu i am :good";
preg_match_all($re, $str, $matches);
So you would need to do something like the following to match the characters up to the space:
preg_match_all('/:[^ ]+/', $string, $matches);
or if you're looking for alpha-only characters you might use the following:
preg_match_all('/:[A-Za-z]+/', $string, $matches);
The array you would look for would be $matches[0] at this point.
print_r($matches)
print_r($matches[0])
You can always reassign the matches sub array with something like this:
$matchesArray = $matches[0]

How to match full words?

I use a simple preg_match_all to find the occurrence of a list of words in a text.
$pattern = '/(word1|word2|word3)/';
$num_found = preg_match_all( $pattern, $string, $matches );
But this also match subset of words like abcword123. I need it to find word1, word2 and word3 when they're occurring as full words only. Note that this doesn't always mean that they're separated by spaces on both sides, it could be a comma, semi-colon, period, exclamation mark, question mark, or another punctuation.
IF you are looking to match "word1", "word2", "word3" etc only then using in_array is always better. Regex are super powerful but it takes a lot of cpu power also. So try to avoid it when ever possible
$words = array ("word1", "word2", "word3" );
$found = in_array ($string, $words);
check PHP: in_array - Manual for more information on in_array
And if you want to use regex only try
$pattern = '/^(word1|word2|word3)$/';
$num_found = preg_match_all( $pattern, $string, $matches );
And if you want to get something like "this statement has word1 in it", then use "\b" like
$pattern = '/\b(word1|word2|word3)\b/';
$num_found = preg_match_all( $pattern, $string, $matches );
More of it here PHP: Escape sequences - Manual search for \b
Try:
$pattern = '/\b(word1|word2|word3)\b/';
$num_found = preg_match_all( $pattern, $string, $matches );
You can use \b to match word boundaries. So you want to use /\b(word1|word2|word3)\b/ as your regex.

Categories