PHP preg_match to find multiple occurrences
You want to use preg_match_all()
. Here is how it would look in your code. The actual function returns the count of items found, but the $matches
array will hold the results:
<?php
$string = "/brown fox jumped [0-9]/";
$paragraph = "The brown fox jumped 1 time over the fence. The green fox did not. Then the brown fox jumped 2 times over the fence";
if (preg_match_all($string, $paragraph, $matches)) {
echo count($matches[0]) . " matches found";
}else {
echo "match NOT found";
}
?>
Will output:
2 matches found
Php preg_match multiple occurrences, return unique array
The solution using preg_match_all
and array_unique
functions:
preg_match_all("~\*\*([^/|*]+)(?=[/|])~", $string, $matches);
$result = array_unique($matches[1]);
print_r($result);
The output:
Array
(
[0] => css
[1] => php
[2] => html
)
(?=[/|])
- positive lookahead assertion which matches word that is followed by one of the characters /|
Update: to ignore tags from match update regex pattern with the following ~\*\*([^/|*<>]+)(?=[/|])~
Regex php preg_match multiple occurrences in string
Thsi regex should work for you:
<?php
$ptn = "#(?:By([A-Za-z]+?))(?=By|$)#";
$str = "findByByteByHouseNumber";
preg_match_all($ptn, $str, $matches, PREG_PATTERN_ORDER);
print_r($matches);
?>
this will be the output:
Array
(
[0] => Array
(
[0] => ByByte
[1] => ByHouseNumber
)
[1] => Array
(
[0] => Byte
[1] => HouseNumber
)
)
Preg_match_all split multiple occurrences
Try this:
$string="59|https://site59.com20|https://site20.com30|https://site30.com16|https://site15.com66|https://site66.com29|https://site29.com";
preg_match_all("/(?:[0-9][0-9](?:\|)(?:https\:\/\/)(.*?)(?=[\d][\d]\||$))|([\d][\d]\|.*)/", $string, $matches);
Results array in $matches:
[0] => 59|https://site59.com
[1] => 20|https://site20.com
[2] => 30|https://site30.com
[3] => 16|https://site15.com
[4] => 66|https://site66.com
[5] => 29|https://site29.com
php find multiple occurence of string in string
Using a regular expression instead of strpos()
is going to be you best bet. I've quickly put the following together which works with your example;
\{PID\s=([0-9]*)\}
You can see a working version here
Use of this in PHP would look like;
$re = '/\{PID\s=([0-9]*)\}/';
$str = 'some text {PID =340} {PID =357}';
preg_match_all($re, $str, $matches);
// Print the entire match result
print_r($matches);
Edit: Edited to return only the actual ID in the matched string. IMO - this is a better solution than the other 2 answers posted as it returns ID's of any length, and only returns ID's matched in the format you've provided.
I've also updated my working example.
Match multiple occurrences in a single regex
You need two entry points, the first is the sentence "There are currently..."
until the opening <p>
tag, and the second starts at the end of the last match after the <br>
tag and the \n
newline.
The first result will use the first entry point, the next results will use the second entry point.
\G
is the anchor that matches the position at the end of the precedent match. This feature is interesting since the preg_match_all
retries to match the pattern until the end of the string. But since \G
is initialized with the start of the string at the begining, we need to avoid this case adding (?!\A)
(not at the start of the string).
Instead of using .+
, I use [^<]+
to avoid to get out of the tag.
To be more readable I use the verbose mode (x modifier) that allows to ignore spaces and to put comments in the pattern. When I need to write literal spaces I put them between \Q
and \E
. All characters between \Q
and \E
are seen as literals (except the pattern delimiter) and spaces are preserved.
$pattern = <<<'EOD'
~ # using this delimiter instead of / avoids to escape all
# the slashes
(?:
# first entry point
\QThere are currently \E
[^<]+?
\Q entries in \E
[^<]+ </b> </p> \n <p>
|
# second entry point
(?!\A)\G
<br>\n
)
\K # removes all that have been matched before from match result
[^<]+ # the string you want
~x
EOD;
if (preg_match_all($pattern, $text, $matches))
var_dump($matches[0]);
PHP: preg_match_all() - how to find all occurrences of OR seperated substrings with a regex correctly?
The order of the regex is important. I'm not sure if this fully solves the issue the method of doing it this way may be fundamentally flawed but you can try this:
$regex = [];
for($i=0;$i<10;$i++) {
$str = "";
for($a=0;$a<10;$a++) {
if($a > $i) {
$str .= $a;
if(strlen($str)>1) {
$regex[] = $str;
}
}
}
}
usort($regex, function($a,$b){
return strlen($b) <=> strlen($a);
});
$myregex = '/'.implode('|', $regex).'/';
What it does is make the number sequences an array, then it sorts them by length and orders them the longest sequences first. The end result is this (after matching)
array(1) {
[0]=>
array(9) {
[0]=>
string(3) "234"
[1]=>
string(2) "12"
[2]=>
string(4) "6789"
[3]=>
string(2) "12"
[4]=>
string(3) "123"
[5]=>
string(5) "45678"
[6]=>
string(2) "12"
[7]=>
string(2) "12"
[8]=>
string(7) "2345678"
}
}
Also note the spaceship operator <=>
only works in PHP7+
Hope it helps.
Sandbox
and not go to the next chars after a match
I don't think this is possible with regex, if you mean you want to find 23
234
2345
all at once in 2345607
for example. However if it matches a long sequence it only stands to reason that it must match a shorter one, logically. So you could just trim off the right hand number until the length is 2 and get the matches.
Related Topics
How to Get the Base Url With PHP
Submitting a Multidimensional Array Via Post With PHP
PHP: Custom Error Handler - Handling Parse & Fatal Errors
How to Upload Multiple Files Using PHP, Jquery and Ajax
Are PHP Include Paths Relative to the File or the Calling Code
File_Get_Contents() Breaks Up Utf-8 Characters
How to Check Uploaded File Type in PHP
How to Generate All Permutations of a String in PHP
How to Put Composite Keys in Models in Laravel 5
Does PHP Have Short-Circuit Evaluation
PHP: Replace Umlauts With Closest 7-Bit Ascii Equivalent in an Utf-8 String
PHP, How to Catch a Division by Zero
How to Check Whether an Array Is Empty Using PHP