Solved

PHP : How to check if the string only contains 1 alphabet?

Posted on 2012-04-12
3
285 Views
Last Modified: 2012-06-27
Hie all,

How to do I check if the string only contains 1 alphabet? For example,

$string = 'AAAAAB'  - false
$string = 'AAAAAA'  - true

I have tried using strpos, preg_match but couldnt suit my needs. I just need to make sure that there is all A in the string.

Thanks.
0
Comment
Question by:bosscat
3 Comments
 
LVL 14

Assisted Solution

by:Scott Madeira
Scott Madeira earned 200 total points
ID: 37839488
This worked for me for some simple examples....

<?php

$string = 'AAABBAA';

if (strlen($string) +1 == count(explode(substr($string, 1,1), $string))){
	// They are the same
	echo 'All same characters';
	
} else {
	// They are different
	echo 'Some different characters';
}
?>

Open in new window

0
 
LVL 12

Accepted Solution

by:
Phil Phillips earned 200 total points
ID: 37840333
This is a slightly less complicated variant of the answer above.

<?php

$string = 'AAABBAA';

if (strlen($string) == substr_count($string, $string{0})) {
   // They are the same
   echo 'All same characters';
}
else {
   // They are different
   echo 'Some different characters';
}

?>

Open in new window


Note that both examples are case-sensitive.  So, if you want 'aaaAA' to return 'true', then you could convert the string to lower case (strtolower()) when running the check.
0
 
LVL 1

Author Closing Comment

by:bosscat
ID: 37840653
Thank you guys... Both ways work excellent.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
This article discusses four methods for overlaying images in a container on a web page
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now