Reputation: 275
I'm struggling to find out how I can get the text after a regex match (until the end of word).
Ex 1:
Input: my home
Regex: /hom/
Result: e
Ex 2:
Input: soulful
Regex: /soul/
Result: ful
Upvotes: 4
Views: 6550
Reputation: 47874
If you only need the trailing text and not the fullstring match, then use \K
to forget previously matched characetrs. This eliminates the need to use a character class and populate a second element in the matches array.
Code: (Demo)
var_dump(preg_match('/hom\K.+/', 'my home', $m) ? $m[0] : '');
// string(1) "e"
var_dump(preg_match('/soul\K.+/', 'soulful', $m) ? $m[0] : '');
// string(3) "ful"
If this is a sanitization task and you know that the substring will be found in the string, then you can use preg_replace()
to match the front of the string. Demo
var_dump(preg_replace('/.*hom/', '', 'my home'));
// string(1) "e"
var_dump(preg_replace('/.*soul/', '', 'soulful'));
// string(3) "ful"
Upvotes: 1
Reputation: 1993
You can expand your regex to match all text after original regex, ie:
$string = 'soulful';
$regex = '/soul(.*)/';
if ( preg_match($regex, $string, $match) ) {
echo 'The text after soul is: '.$match[1].PHP_EOL;
}
Upvotes: 1
Reputation: 44823
Just change your regex to use a group with (
and )
:
$string = 'soulful';
$regex = '/soul(.+)/';
preg_match($regex, $string, $matches);
var_dump($matches);
Output:
array(2) {
[0]=> string(7) "soulful"
[1]=> string(3) "ful"
}
Upvotes: 2
Reputation: 784998
You can use:
$str = 'soulful';
$reg = '/soul(\w+)/';
if ( preg_match($reg, $str, $m) )
print_r ($m);
Array
(
[0] => soulful
[1] => ful
)
Upvotes: 6