Search code examples
phppreg-matchstrpos

Use preg_match() to find start/stop positions of a substring matching a pattern


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];