Jump to content

Writing a regex for "Not X"


Buyocat

Recommended Posts

I want to find the first character which is NOT alphanumeric (also quotes are allowed), but I'm not sure how to express that in regex.  Can anyone lend a hand?  The closest I can get is: /\W/ which almost works except it doen't catch the quote (double or single) correctly.

 

Thanks!

Link to comment
Share on other sites

That should work, but it will bypass _. [^A-Za-z0-9] is better (unless you're also dealing with "special" characters, like ß).

 

Does this not show a double quote for you?

 

<pre>
<?php
$string = 'abc0976123kmhsfkshdf"!(*';
preg_match('/\W/', $string, $matches);
print_r($matches);
?>
</pre>

Link to comment
Share on other sites

I actually get an error running your script for some reason:

Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in /Users/Kanti/Sites/test.php on line 3

 

At any rate I ran my own test and find that the double quote and single quote do not pass through the current regex.  Again, I want to find the first character which is not alphanumeric or a quote (single or double).  As for symbols such as hyphons and underscores, I'm willing to have them work or not.

 

Thanks for your response.

 

Link to comment
Share on other sites

Ya, I'm not sure why it was failing.  I only spent a few minutes trying to fix it, but failed.  It's odd since my own code is

 

public static function findFirst($haystack, $pattern) {
	preg_match($pattern, $haystack, $matches, PREG_OFFSET_CAPTURE);
	if (empty($matches))
		return -1;
	return $matches[0][1];
}

So, its very similar.  Maybe the lack of the flag was the problem?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.