I want to find all the words that contain a specified group of letters, for example if I want to search the with the group of letter ph int the text phone find phill phdas I want the REGEXP to return me phill phone phdas I dont want to do it in another way than REGEXP. (PHP)
You can use this regex:
/\w*ph\w*/
That will match 0 or more word characters, followed by your search term ph, followed by 0 or more word characters.
RegEx Demo
PHP Code:
$kw = 'ph';
preg_match_all('/\w*' . $kw . '\w*/', $str, $matches);
You can use the Pregmatch function of php and as it's first argument give the regex as /\wph\w/. Give stars after the w as well , that is for any character present..
Try this:
<?php
$subject = "your subject";
$pattern = '//\w*ph\w*//';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);
?>
Related
I need to find a number followed by a specific string, within another string.
The initial string could be:
some text 0.25mcg some more text
some text 25mcg some more text
so the number could be a decimal. I need to be able to return the number (so 0.25 or 25) where ever the number is followed by 'mcg'
Can anyone help me out. This doesn't work:
if(preg_match('(\d+mcg)', $item, $match))
Another option is to capture a digit with an optional decimal part \d+(?:\.\d+)? and use a word boundary \b to prevent the match being part of a larger word.
\b(\d+(?:\.\d+)?)mcg\b
Regex demo | Php demo
Code example
$re = '/\b(\d+(?:\.\d+)?)mcg\b/';
$str = 'some text 0.25mcg some more text some text 25mcg some more text';
preg_match_all($re, $str, $matches);
print_r($matches[1]);
Output
Array
(
[0] => 0.25
[1] => 25
)
If you want a match only instead of a capturing group you might also opt for a positive lookahead (?= instead.
\b\d+(?:\.\d+)?(?=mcg\b)
Regex demo | Php demo
It's a job for preg_match_all
preg_match_all('/([\d.]+)mcg/', $item, $matches);
[\d.]+ matches 1 or more digits or dot.
here is simple version:
<?php
$item1 = 'some text 0.25mcg some more text';
$item2 = 'some text 25mcg some more text';
if (preg_match('/([0-9\\.]+)\\s*mcg/', $item1, $match)) echo $match[1] . '<br>';
if (preg_match('/([0-9\\.]+)\\s*mcg/', $item2, $match)) echo $match[1] . '<br>';
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.
i'm not very firm with regular Expressions, so i have to ask you:
How to find out with PHP if a string contains a word starting with # ??
e.g. i have a string like "This is for #codeworxx" ???
I'm so sorry, but i have NO starting point for that :(
Hope you can help.
Thanks,
Sascha
okay thanks for the results - but i did a mistake - how to implement in eregi_replace ???
$text = eregi_replace('/\B#[^\B]+/','\\1', $text);
does not work??!?
why? do i not have to enter the same expression as pattern?
Match anything with has some whitespace in front of a # followed by something else than whitespace:
$ cat 1812901.php
<?php
echo preg_match("/\B#[^\B]+/", "This should #match it");
echo preg_match("/\B#[^\B]+/", "This should not# match");
echo preg_match("/\B#[^\B]+/", "This should match nothing and return 0");
echo "\n";
?>
$ php 1812901.php
100
break your string up like this:
$string = 'simple sentence with five words';
$words = explode(' ', $string );
Then you can loop trough the array and check if the first character of each word equals "#":
if ($stringInTheArray[0] == "#")
Assuming you define a word a sequence of letters with no white spaces between them, then this should be a good starting point for you:
$subject = "This is for #codeworxx";
$pattern = '/\s*#(.+?)\s/';
preg_match($pattern, $subject, $matches);
print_r($matches);
Explanation:
\s*#(.+?)\s - look for anything starting with #, group all the following letters, numbers, and anything which is not a whitespace (space, tab, newline), till the closest whitespace.
See the output of the $matches array for accessing the inner groups and the regex results.
#OP, no need regex. Just PHP string methods
$mystr='This is for #codeworxx';
$str = explode(" ",$mystr);
foreach($str as $k=>$word){
if(substr($word,0,1)=="#"){
print $word;
}
}
Just incase this is helpful to someone in the future
/((?<!\S)#\w+(?!\S))/
This will match any word containing alphanumeric characters, starting with "#." It will not match words with "#" anywhere but the start of the word.
Matching cases:
#username
foo #username bar
foo #username1 bar #username2
Failing cases:
foo#username
#username$
##username
I have a string as
This is a sample text. This text will be used as a dummy for "various" RegEx "operations" using PHP.
I want to select and replace all the first alphabet of each word (in the example : T,i,a,s,t,T,t,w,b,u,a,d,f,",R,",u,P). How do I do it?
I tried /\b.{1}\w+\b/. I read the expression as "select any character that has length of 1 followed by word of any length" but didn't work.
You may try this regex as well:
(?<=\s|^)([a-zA-Z"])
Demo
Your regex - /\b.{1}\w+\b/ - matches any string that is not enclosed in word characters, starts with any symbol that is in a position after a word boundary (thus, it can even be whitespace if there is a letter/digit/underscore in front of it), followed with 1 or more alphanumeric symbols (\w) up to the word boundary.
That \b. is the culprit here.
If you plan to match any non-whitespace preceded with a whitespace, you can just use
/(?<!\S)\S/
Or
/(?<=^|\s)\S/
See demo
Then, replace with any symbol you need.
You may try to use the following regex:
(.)[^\s]*\s?
Using the preg_match_all and implode the output result group 1
<?php
$string = 'This is a sample text. This text will be used as a dummy for'
. '"various" RegEx "operations" using PHP.';
$pattern = '/(.)[^\s]*\s?/';
$matches;
preg_match_all($pattern, $string, $matches);
$output = implode('', $matches[1]);
echo $output; //Output is TiastTtwbuaadf"R"uP
For replace use something like preg_replace_callback like:
$pattern = '/(.)([^\s]*\s?)/';
$output2 = preg_replace_callback($pattern,
function($match) { return '_' . $match[2]; }, $string);
//result: _his _s _ _ample _ext. _his _ext _ill _e _sed _s _ _ummy _or _various" _egEx _operations" _sing _HP.
I'm trying to script and parse a file,
Please help with regex in php to find and replace the following patterns:
From: "This is a foo[/www/bar.txt] within a foo[/etc/bar.txt]"
To: "This is a bar_txt_content within a bar2_txt_content"
Something along those lines:
$subject = "This is a foo[/www/bar.txt] within a foo[/etc/bar.txt]";
$pattern = '/regex-needed/';
preg_match($pattern, $subject, $matches);
foreach($matches as $match) {
$subject = str_replace('foo['.$match[0].']', file_get_contents($match[0]), $subject);
}
And my second request is to have:
From: 'This is a foo2[bar bar ] bar bar].'
To: "this is a returned"
Something along those lines:
$subject = 'This is a foo2[bar bar \] bar bar].';
$pattern = '/regex-needed/';
preg_match($pattern, $subject, $matches);
foreach($matches as $match) {
$subject = str_replace('foo2['.$match[0].']', my_function($match[0]), $subject);
}
Please help in constructing these patterns...
If you always have a structure like foo[ ... ]
Then is very easy:
foo\[([^]]+)\]
That is .NET syntax but i'm sure the expressions is simple enough for you to convert.
Description of the regex:
Match the characters “foo” literally «foo»
Match the character “[” literally «[»
Match the regular expression below and capture its match into backreference number 1 «([^]]+)»
Match any character that is NOT a “]” «[^]]+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “]” literally «]»
Luc,
this should help you get started.
http://php.net/manual/en/function.preg-replace.php
You may have to setup a loop and increase the counter, using preg_replace with a limit of 1 to replace only the first instance.
In order to match foo[/www/bar.txt]:
the regex should be something like:
foo\[\/www\/([A-Za-z0-9]*)\.txt\]
The backslashes are there to cancel the special meaning of some characters in your regexp.
It will match foo[/www/.[some file name].txt, and ${1} will contain the filename without the .txt as brackets form groups which can be used in the replaced expression. ${1} will contain what was matched in the first round brackets, ${2} will contain what was matched in the second one, etc ...
Therefore your replaced expression should be something like "${1}_txt_content". Or in the second iteration "${1}2_txt_content".
[A-Za-z0-9]* means any alphanumeric character 0 or more times, you may want to replace the * with a + if you want at least 1 character.
So try:
$pattern = foo\[\/www\/([A-Za-z0-9]*)\.txt\];
$replace = "${1}_txt_content";
$total_count = 1;
do {
echo preg_replace($pattern, $replace, $subject, 1, $count);
$replace = "${1}" + ++$total_count + "_txt_content";
} while ($count != 0);
(warning, this is my first ever PHP program, so it may have mistakes as I cannot test it ! but I hope you get the idea)
Hope that helps !
Tony
PS: I am not a PHP programmer but I know this works in C#, for example, and looking at the PHP documentation it seems that it should work.
PS2: I always keep this website bookmarked for reference when I need it: http://www.regular-expressions.info/
$pattern = '/\[([^\]]+)\]/';
preg_match_all($pattern, $subject, $matches);
print_r($matches['1']);
found the correct regex I needed for escaping:
'/foo\[[^\[]*[^\\\]\]/'