Nick
Nick

Reputation: 14293

PHP truncate string on first number

I have a simple question, as I'm new to PHP.

I have a textbox that sends via AJAX a post request to a php file. This php file checks if there's a file with the same name typed by the user into the textbox inside a specific folder. Everything works till now.

Now, my files are named with just letters, and no more than 2. With the following code, i'm able to truncate the search string to just 2 characters

if ($_REQUEST) {
     $q = $_REQUEST['search'];
     $checkFilename = substr($q , 0, 2);

     $fileCSV = "Data/CSV/" . $checkFilename . ".csv";

     if(file_exists($fileCSV)){
        foreach (glob($fileCSV) as $file) {
        $file_handle = fopen($file, "r");
        while (!feof($file_handle)) {
            $line = fgets($file_handle);
            echo $line;
        }
        fclose($file_handle);
    }
     } else {
        echo "This file doesn't exist!";
     }      
};

but now my problem is:

What if the second character is a number? As I told you, my files name is formed by just 2 letters.

How can then truncate the string to the first character if the second one is a number?

Hope is clear enough, as english is not my mother tongue.

Cheers

Upvotes: 2

Views: 109

Answers (2)

Justin Bell
Justin Bell

Reputation: 396

A regular expression could work:

$checkFilename = preg_replace("%^([a-zA-Z]{1,2}).*$%", "\\1", $checkFilename);

From the start of the string, looking for between 1 and 2 characters between A-Z and a-z, and ignoring the rest, you can get the leading filename characters.

Consider the following (run in a PHP interpreted console):

php > echo preg_replace("%^([a-zA-Z]{1,2}).*$%", "\\1", "sf3fw34");
sf

php > echo preg_replace("%^([a-zA-Z]{1,2}).*$%", "\\1", "s3dfs");
s

Upvotes: 1

Tibor B.
Tibor B.

Reputation: 1690

There are many different ways of doing this, using regular expressions, and searching in a text, etc... But I'd go with this one:

Change the $checkFilename = substr($q, 0, 2); to:

$checkFilename = trim(substr($q, 0, 2), "0123456789");

It would remove any numbers from the end.

Upvotes: 2

Related Questions