简体   繁体   中英

How to separate string into parts in PHP

Right Now I Have:

$path2 = $file_list1; 
$dir_handle2 = @opendir($path2) or die("Unable to open $path2"); 
while ($file2 = readdir($dir_handle2)) { 
if($file2 == "." || $file2 == ".." || $file2 == "index.php" ) 
continue; 
echo ''.$file2.'<br />'; 
} 
closedir($dir_handle2);
echo '<br />';

When $file2 is returned, the last 4 characters in the string will always end in a number plus the file extension .txt, like this:

file_name_here1.txt
some_other-file10.txt

So my question is, how can I separate $file2 so it returns the string in two parts, $file_name and $call_number like this?:

echo 'File: '.$file_name.' Call: '.call_number.'<br />';

Returns:

File: file_name_here Call: 1
File: some_other-file Call: 10

instead of this:

echo ''.$file2.'<br />';

Returns:

file_name_here1.txt
some_other-file10.txt

Thanks....

Try this, you need to use Regex to do this effectively

$filename = reset(explode(".", $file2))
preg_match("#(^[a-zA-Z\_\-]*)([\d]*)#", $filename, $matches);
$fullMatch = $matches[0];
$file = $matches[1];
$call = $matches[2];

echo "File: " . $file . " Call: " . $call;

Use regular expressions:

preg_match("/^(.+)(\d+)(\..+)$/", $file2, $matches);
$file_name = $matches[1];
$call_number = $matches[2];

I'm a big advocate of Regex but I decided to go slightly different here. Check it out:

$file = 'file_name_here19.txt';
$file_parts = pathinfo($file);
$name = $file_parts['filename'];
$call = '';
$char = substr($name, strlen($name) - 1);
while(ord($char) >= 48 && ord($char) <= 57) {
    $call = $char . $call;
    $name = substr($name, 0, strlen($name) - 1);
    $char = substr($name, strlen($name) - 1);
}
echo 'Name: ' . $name . ' Call: ' . $call;
  1. Use pathinfo() function to cut off file extension.
  2. Use preg_match() function to separate name from number. 3.

     while (...) { ... $filename; // some_other-file10.txt $filename = pathinfo($filename, PATHINFO_FILENAME); // some_other-file10 preg_match('/^(?<name>.*?)(?<number>\\d+)$/', $filename, $match); $match['name']; // some_other-file $match['number']; // 10 echo "File: {$match['name']} Call: {$match['number']}\\n"; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM