Use preg_match () to find the start and end positions of a substring matching a pattern

I want to copy a substring of a string using PHP.

The regular expression for the first pattern is /\d\|\d\w0:/

The regular expression for the second pattern is /\d\w\w\d+:\s-\s:/

Is it possible to combine preg_match with strpos to get exact positions from start to finish, and then copy it with:

 substr( $string, $firstPos,$secPos ) ? 
+4
source share
4 answers

I'm not sure, but maybe you could use preg_split for this:

 $mysubtext = preg_split("/\d\|\d\w0:/", $mytext); $mysubtext = preg_split("/\d\w\w\d+:\s-\s:/", $mysubtext[1]); $mysubtext = $mysubtext[0]; 
+4
source

Of course.

Or you could combine the patterns into a new super-awesome-magical that matches the content between them (asserting that the prefix appears immediately before the subscript 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]; } 

(Other than that: you probably want to use the s modifier or something other than . If your substring spans multiple lines.)

+3
source

When using the fourth preg_match() parameter, you can even set the PREG_OFFSET_CAPTURE flag PREG_OFFSET_CAPTURE that the function returns the offset of the matched string. Therefore, it should not be necessary to combine preg_match() and strpos() .

http://php.net/manual/function.preg-match.php

+3
source

The third argument to preg_match is the output parameter that collects your captures, i.e. matching strings that match. Use those to feed your objects. Stanzas will not accept regular expressions, but entries will contain the actual matched text that is contained in your line. Use brackets to perform captures.

For example (not tried, but 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, ie 'bbb' // now feed $regs[1] to strpos, to find its position 
0
source

Source: https://habr.com/ru/post/1312941/


All Articles