View Full Version : PHP Code to check if phrase contains only numbers

Cloud Ghost
03-25-2010, 09:01 AM

I need a PHP code using the preg_match() function to check if a phrase contains numbers. I also need another code to make sure a phrase only contains letters, numbers, hyphens or underscores. If anyone could make one that would be great. :D

03-25-2010, 09:32 AM
use the is_numeric function e.g. is_numeric($string); or preg_match('/[^0-9]/',$string); and for letters, numbers etc use preg_match('/[^0-9a-zA-Z-_]/',$string);

03-25-2010, 01:18 PM
There is also http://www.php.net/ctype_digit

Cloud Ghost
03-26-2010, 01:46 AM
@DJCMBear Thanks! Why did you remove the ^ out of the code though because I realized my code is only working with that.
@kbluhm :o Thanks! That might be handy in the future. *bookmarks*

03-26-2010, 02:29 AM
i didnt know i did lol ill put it back in. and the ^ means not so if ^0-9 that if not a number.

Cloud Ghost
03-30-2010, 06:17 AM
Hello Again,

I just added a tag system to my content management system. When I add a post with tags it will look like this in the database for example: red,blue,yellow,pink
When I select the tags from the database I want to make them display on the page like this if you were to view the page source:

<a href="/index.php?tag=red">red</a>, <a href="/index.php?tag=blue">blue</a>, <a href="/index.php?tag=yellow">yellow</a>, <a href="/index.php?tag=pink">pink</a>
Could someone help me with this and is it possible to use preg_replace() to do this?

03-30-2010, 10:46 AM
Not sure I understand what you want but...

$sql = "SELECT tag from TABLE_TAGS";

$result = mysql_query($sql) or die('SQL Error !<br>'.$sql.'<br>'.mysql_error());
$rows = mysql_num_rows($result);

while ($i < $rows) {

$data = mysql_fetch_array($result);

echo "<a href=\"/index.php?tag=" . $data['tag'] . "\">" . $data['tag'] . "</a>, ";



Of course, you will have to replace 'tag' and TABLE_TAGS with the correct names.

Cloud Ghost
03-31-2010, 02:30 AM
Not exactly. That wouldn't work because the tags are saved in one row like this for example: red,green,blue,yellow And I need to code that will make each one a link and make them appear like this:
red, green, blue, yellow

04-01-2010, 02:42 PM
Why not use EXPLODE then?
Then a foreach loop should do the trick.