php:string是双引号,不是单引号。怎么修?

时间:2017-01-28 16:43:43

标签: php string http-post double-quotes

我问this SO question php: split string into 3 parts...并得到了很好的答案。但是,我遇到了一个问题。问题是双引号字符串要处理。因此,当$符号在字符串中时,它在预期的情况下不能正常工作。

$str = $_POST['source'];//comes double-quoted, example: "$abc$";

这样来自上述问题答案的代码是:

<?php
$str = "$abc$$$";//comes from _POST['source'];

preg_match('/^([^\w]*)(\w+.*\w+)?([^\w]*)$/iu', $str, $matches);
$parts = array_slice($matches, 1);

print_r($parts);
?>

不起作用并导致E_NOTICE : type 8 -- Undefined variable: 从我发现的问题是"$abc$$$"是双引号,而不是单引号。这导致$ treat作为变量:SO: Dollar ($) sign in password string treated as variable

我试过

$str = $_POST['source'];
$str = (string)$str;// I hoped to convert "$abc$$$" to '$abc$$$' (to make single-quoted)

但这没有用。 任何想法如何面对这个问题?

1 个答案:

答案 0 :(得分:1)

它运作得很好。 导致问题的测试。

改为

$_POST['source'] = '$abc$$$';

$str = $_POST['source'];

preg_match('/^([^\w]*)(\w+.*\w+)?([^\w]*)$/iu', $str, $matches);
$parts = array_slice($matches, 1);

print_r($parts);

结果

Array
(
    [0] => $
    [1] => abc
    [2] => $$$
)

附加示例

看看这个简单的测试。我使用单引号字符串加载变量,var_dump将其显示为双引号字符串。

$test = '$var';
var_dump($test);

结果

string(4) "$var"

它只是转储函数决定显示字符串的方式,字符串尚未更改

仅当在PHP本身内部时,在使用双引号字符串文字创建字符串变量时才使用$进行此变量扩展。这是PHP所做的事情,并没有关于双引号文字的内在。

所以这个

$test = "$var";

如果$var不存在则会生成错误,如果存在则会展开错误。但这只是因为它是用PHP代码完成的。

相关问题