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;

输出:$%&$%&

live demo

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

您几乎已经掌握了!只需将 "another variable" 添加为 匹配 参数:

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

请注意 $special_characters 将是一个 array.

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

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

)