Jump to content

Recommended Posts

I'm not sure how to word this well enough to even perform a search, but here's what I want to do:

 

I have a field whose value is a filename. I want to look at that name and return one set of code if the name starts with a letter (a-z) and another if it's a number (1-9).

 

Something like:

 

if ($filename starts with letter) {
echo "code 1";
} else if ($filename starts with number) {
echo "code 2";
}

 

I just don't know how, or if, that's doable. Is there something boneheadedly simple I'm don't know about?

You can access the first character with $filename[0], and then use ctype_alpha() and ctype_digit() to check for alphabetic or numeric chars (0-9).

 

<?php
$filename = 'alpha';
if (ctype_alpha($filename[0])) {
//first char alphabetic
} elseif (ctype_digit($filename[0])) {
//first char numeric
}
?>

OK, I'm not having luck with either these. Let me start with the first one.

 

I'm assuming that in the following:

$str = "123abc";

I need to plug in my variable for '123abc', so it would look something like:

 

$str = "$filename";

Right? That should get the actual filename text (or numbers) for the script to work with. I keep getting the 'unexpected T_Variable error on that line (in both examples) every time.

 

Thanks for the help.

I'm obviously missing something (and given that I'm still learning my way through php, that's not surpnising). But this is the entirety of the php code I'm working with:

 

<?php

$searchcriteria = array();
$searchcriteriausingquotes = array(('file'));

if (array_key_exists('file', $_GET)) {
    $file = $_GET['file'];
    if (strlen($file)) $searchcriteria['file'] = $file;
}

$str = $file;

if (ctype_digit($str[0]) === TRUE ) {
echo 'Starts with a number';
} else {
echo 'Starts with a non-number';
}

?>

 

I tried a hybrid of the two suggestions above, but I'm getting an 'unexpected T_String' error on the following line:

 

if (ctype_digit($str[0]) === TRUE ) {

 

Any thoughts on why?

 

 

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.