PHP-将一个字符串中的特殊字符放入另一个字符串


PHP - Put special characters from a string into another string

我有一个函数,我想告诉我字符串中有哪些特殊字符。

我不想去掉它们,我想把它们放入另一个变量中。

if (preg_match('/[''^£$%&*()}{@#~?><>,|=_+¬-]/', $string)) {
    $special_characters = special characters from $string
}

有办法做到这一点吗?

感谢

试试这个:

$string = 'sds$%&dd$%&gfhfh';
$string = preg_match_all ('/[''^£$%&*()}{@#~?><>,|=_+¬-]/', $string, $result);
$output = '';
foreach($result[0] as $r){
$output .= $r;
}
echo $output;

输出:$%&$%&

请参阅实时演示

preg_match('/[''^£$%&*()}{@#~?><>,|=_+¬-]/', $string, $matches);
var_dump($matches);

您实际上已经拥有了它!只需在匹配参数时添加"另一个变量":

if(preg_match_all('/[''^£$%&*()}{@#~?><>,|=_+¬-]/', $string, $special_characters)) {
  print_r($special_characters);
}

请注意,$special_characters将是数组

因此,对于$string = "$450 is the total cost, which is about 20% of the income.";,您将拥有:

Array
(
    [0] => Array
        (
            [0] => $
            [1] => ,
            [2] => %
        )
)