John Davidson

php - Why regex with lookaheads doesn't match?

0 comments
Message:


I need (in PHP) to split a sententse by the word that cannot be the first or the last one in the sentence. Say the word is "pression" and here is my regex


/^.+?(?=[\s\.\,\:\;])pression(?=[\s\.\,\:\;]).+$/i

Live here: https://regex101.com/r/CHAhKj/1/


First, it doesn't match.
Next, I think - it is at all possible to split that way? I tryed simplified example


print_r(preg_split('/^.+pizza.+$/', 'my pizza is cool'));

live here http://sandbox.onlinephpfunctions.com/code/10b674900fc1ef44ec79bfaf80e83fe1f4248d02


and it prints an array of 2 empty strings, when I expect
['my ', ' is cool']



My Answer:
Regex with lookaheads in PHP can be useful for more complex pattern matching and extracting specific information from a string. Lookaheads allow you to check for a pattern without actually consuming the characters in the string, which can be helpful in cases where you need to match a certain pattern but don't want to include it in the final match result.

For example, you can use a positive lookahead to match a string that is followed by a specific pattern, without including the pattern itself in the match result. This can be useful for extracting information from a string without including unnecessary characters.

Overall, regex with lookaheads can help you write more precise and efficient patterns for matching and extracting information from strings in PHP.

Rate this post

3 of 5 based on 3768 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us