Reputation: 7094
i am using preg_match function and i want to get the unmatched text with it. This is my code:
<?php
$subject = "abcdef ghij";
$pattern = '/^def/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>
Can i retrieve the part of the string, that is not matching "abcdef" in the above string, using preg_match?
Upvotes: 1
Views: 1421
Reputation: 455132
$subject = "abcdef ghij";
$key = 'def';
$non_match = '';
if(preg_match("/^(.*)$key(.*)$/",$subject,$m)) {
$non_match= $m[1].$m[2];
}
Upvotes: 2
Reputation: 11779
The simpler way is to split string ( explode or preg_split ), then run foreach and remove unmatched parts
$subject = "abcdef ghij"; $subject = explode( " ", $subject ); foreach( $subject as $k => $v ) if( preg_match( "/abcdef/", $v )) { unset( $subject[$k] ); } $subject = implode( " ", $subject );
Upvotes: 1