PHP 从字符串获取或打印 Specialchar、数字、字母分隔 PHP 中的分隔符


php from a string get or print specialchar, number, alphabetic seprate seprate in php

我有一个字符串,如下所示:

$str = "hello@$how%&*!are345You^_THere56";

我希望字母表存储在一个变量中,例如:

hello,how,are,you,THere

数字应存储在一个变量中,例如:

3,4,5,5,6

特殊字符分别:

@$%&*!^_

我该怎么做?

在我看来,最好的选择是使用 preg_split

<?php
$str = 'hello@$how%&*!are345You^_THere56';
$words = array_filter(preg_split('/[^a-zA-Z]/', $str));
$numbers = str_split(join('', preg_split('/[^0-9]/', $str)));
$specials = str_split(join('', preg_split('/[a-zA-Z0-9]/', $str)))
print_r($words);
print_r($numbers);
print_r($specials);

通过否定字符类,我们可以按照我们想要的方式过滤结果。join呼叫str_split是按角色而不是按组进行拆分。

结果:

Array
(
    [0] => hello
    [2] => how
    [6] => are
    [9] => You
    [11] => THere
)
Array
(
    [0] => 3
    [1] => 4
    [2] => 5
    [3] => 5
    [4] => 6
)
Array
(
    [0] => @
    [1] => $
    [2] => %
    [3] => &
    [4] => *
    [5] => !
    [6] => ^
    [7] => _
)

您可以检查正则表达式匹配。

$str = "hello@$how%&*!are345You^_THere56";
for($i=0; $i<strlen($str ); $i++) 
     if($str[$i] == "^[0-9]*$") {
           //store numbers
      }
     else-if($str[$i] == "^[a-zA-Z]*$") {
     // store characters
       }
    else {
       //store special characters
      }

试试这个

$strs = '';
$num = '';
$sc = '';
$str = 'hello@$how%&*!are345You^_THere56';
$a = str_split($str);
$prev = '';
foreach($a as $v){
    switch($v){
        case is_numeric($v):
            $num .= $v;
            break;
        case preg_match('/[a-zA-Z]/',$v):
                $sc .= $v;
            break;
        default:
            $strs .= $v;
            break;
    }
    $prev = $v;
}
echo "<p>";
echo "<p>Strings: ".$strs."</p>";
echo "<p>Numbers: ".$num."</p>";
echo "<p>Special Characters: ".$sc."</p>";