Check if string contains an underscore in PHP?

$str = 'foo_bar'; if (preg_match('/^a-z+_a-z+$/i', $str)) { // contains an underscore and is two words } else { // does not contain two words, or an underscore }.

Preg_match('/. +_. +/','foo__') == 1 – Mchl Jul 25 at 20:12 1 Need to filter spaces too.

– Ivan Nevostruev Jul 25 at 20:12 How is that now? :) – Shef Jul 25 at 20:16 Better now, although I don't think %! ^_#*$ would be a valid word ;P – Mchl Jul 25 at 20:18 @Mchl: Well, that's up to the OP to specify exactly what chars it will contain.

However, I think we finally got there now, didn't we? – Shef Jul 25 at 20:21.

I like this one, the best so far I think – Mchl Jul 25 at 20:20 Definitely the best one. Inside the character classes for easier readibility and less confusion a lower case w is used, usually. There is no need to add the underscore inside the character class, \w includes it.

The correct regex would be ^\w+_\w+$. – Shef Jul 25 at 20:48 3 @Shef Nope. Your regex will also match aaa_bbb_ccc :) – Karolis Jul 25 at 20:56 2 ^\w+_\w+$ matches ___ however, while ^^\W_+_^\W_+ does not.

– Mchl Jul 25 at 20:57 You are right! Exclusion is the way to go. :) – Shef Jul 25 at 20:59.

For example: preg_match('#^a-zA-Z1-9+_a-zA-Z1-9+$#','foo_bar'); See here for some really good tutorial on what all that means.

– Alexwhin Jul 25 at 20:09 1 Of course you could – Mchl Jul 25 at 20:11.

$mystring = "hello_there"; $pos = strpos($mystring, '_'); if(false! == $pos) { //no _ in the mystring } else { echo "_ found at pos ". $pos; } //in this example else part will execute.

Here you go: php.net/manual/en/function.substr-count.php You could also do something like: count( array_filter( explode( '_', str_replace( " ", "_", "foo_bar" ) ) ) ) // == 2.

Count(explode('_','_')); // ==2 – Mchl Jul 25 at 20:13 Indeed, thanks. Added array_filter() ;) – Johan Jul 25 at 20:17 Not really: count( array_filter( explode( '_', "lorem ipsum _ foo bar" ) ) ) //==2 – Mchl Jul 25 at 20:46 Well then, added a str_replace( " ", "_" ) ;) – Johan Jul 25 at 20:53.

You could even do a simple $x = explode('_', $string) and then see if there is a result with count($x).

If(str_replace("_", "", $x)! = $x) { // There is an underscore }.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions