John Davidson

regex - preg_match_all - exclude a word from the search php

0 comments
Message:


I want to exclude a class from this regex, for example "apple" or "apple-tree"


preg_match_all('/class[~=]+[\'"](.*?)[\'"]/i', $html, $matches1, PREG_SET_ORDER, 0);

How would I achieve this in php regex?



My Answer:
To exclude a specific word from a regex search using `preg_match_all` in PHP, you can use a negative lookahead assertion. Here's an example:

php
$string = "This is a sample text with some words.";
$pattern = '/\b(?!exclude\b)\w+\b/';

preg_match_all($pattern, $string, $matches);

print_r($matches[0]);


In this example, the regex pattern `\b(?!exclude\b)\w+\b` will match all words in the string except for the word "exclude". The negative lookahead `(?!exclude\b)` ensures that the word "exclude" is not included in the match.

You can replace "exclude" with the word you want to exclude from the search.

Rate this post

4 of 5 based on 4254 votes

Comments




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