Use preg_match() to find start/stop positions of a substring matching a pattern
-
27-09-2019 - |
Question
I want to copy a substring of a string using PHP.
The regex for the first pattern is /\d\|\d\w0:/
The regex for the second pattern is /\d\w\w\d+:\s-\s:/
Is it possible combining preg_match
with strpos
to get the exact positions from start to end and then copy it with:
substr( $string, $firstPos,$secPos ) ?
Solution
i'm not sure, but maybe you could use preg_split for that like this:
$mysubtext = preg_split("/\d\|\d\w0:/", $mytext);
$mysubtext = preg_split("/\d\w\w\d+:\s-\s:/", $mysubtext[1]);
$mysubtext = $mysubtext[0];
OTHER TIPS
Sure.
Or, you could combine the patterns into a new super-awesome-magical one which matches the content between them (by asserting that the prefix occurs immediately before the matched substring, and the suffix occurs immediately after it).
$prefix = '\d|\d\w0:';
$suffix = '\d\w\w\d+:\s-\s:';
if (preg_match("/(?<=$prefix).*?(?=$suffix)/", $subject, $match)) {
$substring = $match[0];
}
(Aside: You'll probably want to use the s
modifier, or something other than .
, if your substring will span multiple lines.)
When using the fourth parameter of preg_match()
you can even set the PREG_OFFSET_CAPTURE
flag to let the function return the offset of the matched string. So there should be no need to combine preg_match()
and strpos()
.
The third argument to preg_match is an output parameter which gathers your captures, i.e. the actual strings that matched. Use those to feed your strpos. Strpos won't accept regular expressions, but the captures will contain the actual matched text, which is contained in your string. To do captures, use the parenthesis.
For example (haven't tried, but it's to get the idea):
$str = 'aaabbbaaa';
preg_match('/(b+)/', $str, $regs );
// now, $regs[0] holds the entire string, while $regs[1] holds the first group, i.e. 'bbb'
// now feed $regs[1] to strpos, to find its position