0
$pattern = "/^[a-zA-Z0-9]{1,30}$/";
$string = preg_replace("Description", "", $description);

if(preg_match($pattern, $string)){
  //do some stuff
}

How would I adjust the regex pattern to fail when "Description" is found in the string.

2 Answers 2

2

You use something called negative lookahead -- a zero-width assertion. This means that it checks something in the string without actually "eating" any of it, so things that follow the assertion start where the assertion started. Negative lookahead means that if it finds the string, the regex fails to match. You do this with (?!...) where "..." is a placeholder for you want to avoid. So in your case, where you want to avoid Description:

$pattern = "/^(?!.*Description)[a-zA-Z0-9]{1,30}$/";

In (?!.*Description), the .* at the beginning is there to make sure Description doesn't appear anywhere at all in the string (i.e. Any number of any characters can come before Description and it will still fail if Description is in there somewhere). And remember, this is zero-width, so after it does the check for not Description, it starts back again where it was, in this case the very beginning of the string.

Sign up to request clarification or add additional context in comments.

3 Comments

I understand the "?!", but I dont understand why the ".*" is necessary. Besides that, it works great.
@Peter, It's necessary because ^ means "anchor at the beginning of the strnig" so if you just did (?!Description), it would only fail if the string started with Description.
Ok I understand now. Thanks for the explaination
0

Don't use a regex for that.

if( strpos($string,"Description") === false) {
    // "Description" is NOT in the string
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.