php从字符串获取或打印specialchar,数字,字母分隔seprate在PHP中

时间:2015-06-19 10:06:22

标签: php

我有一个字符串:

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

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

hello,how,are,you,THere

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

3,4,5,5,6

单独的特殊字符:

@$%&*!^_

我该怎么做?

3 个答案:

答案 0 :(得分:0)

在我看来,最好的选择是使用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);

通过否定字符类,我们可以按照我们想要的方式过滤结果。 str_splitjoin来电是基于字符而不是以群组为基础进行拆分的。

结果:

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] => _
)

答案 1 :(得分:0)

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

$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
      }

答案 2 :(得分:0)

试试这个

$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>";