Jump to content

Check String for Chars


darkhappy

Recommended Posts

How can I check $var for characters 0 - 9 and a -z (and what ohter normal charactes should I look for?)?

 

 

I am processing a value from a CSV file if I run the check if ($var!='') on some of the fields it returns TRUE even though the CSV field is empty, so I need to check the $var to make sure it contains data. Please let me know if this question does not make sense so I can re-phrase or give more info.

 

 

 

Thank you,

dhappy

Link to comment
Share on other sites

Best solution for you would be using ctype_alnum(). It's more efficient than using a regular expression, and it does the job.

 

 

The regex way:

 

<?php

if(preg_match("/^[a-z0-9]*$/i", $str)) 
{
   //$str is valid
}

?>

 

 

Orio.

 

I have tried both ways and empty fields are still evaluating to true. What am I doing wrong?

 

 

Here is my code:

 

	<?php
foreach($checkarr1 as $v4) {
		if(ctype_alnum($v4)) {
			echo "'".$v4."'-";
		}
}
?>

 

 

$checkarr1 is an array created from a row in a CSV file, some values are null and I only want to echo $v4 for valid fields. I put '' around the var so I can see the blanks when it outputs.

 

 

 

thanks,

dhappy

Link to comment
Share on other sites

Missed your comment about the empty fields. Here's the ctype_alnum() fix. sasa's solution would, of course, also work.

 

<?php
foreach($checkarr1 as $v4)
{
if(!empty($v4) && ctype_alnum($v4))
	echo "'".$v4."'-";
}
?>

 

 

Orio.

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.