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
https://forums.phpfreaks.com/topic/68164-writing-a-regex-for-not-x/
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>

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.

 

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?

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.