正则表达式不在PHP中的括号之间打印字符串

时间:2015-04-07 22:55:20

标签: php regex

我上下研究过这个我无法弄清楚我做错了什么。我有以下变量,我从$ _GET得到。

$monitorname = $_GET['monitorname'];

应该看起来类似于:985_Sands-Road(54dd14d80bd5f777184cb9c8),在它实际上看起来像这样的网址:

index.php?monitorname=985_Sands-Road%26%2340%3B54dd14d80bd5f777184cb9c8%26%2341%3B&alertType=0"

我正在尝试使用正则表达式来获取括号之间的文本,这是我的正则表达式代码:

preg_match('/\(([^)]+)\)/', $monitorname, $match);
$id = $match[1];
echo $id;

但无论我做什么,它都不会回复ID。我能看到什么并解决这个问题?必须注意的是,当我将字符串显式保存为变量时,它可以正常工作:

$text = '985_Sands-Road(54dd14d80bd5f777184cb9c8)';
preg_match('/\(([^)]+)\)/', $text, $match);
$id = $match[1];
echo $id;

非常感谢

2 个答案:

答案 0 :(得分:2)

看,GET数据是URL ENCODED。 您需要使用string urldecode ( string $str )进行解码并string html_entity_decode ( string $string [, int $quote_style [, string $charset ]] )

`html_entity_decode(urldecode("985_Sands-Road%26%2340%3B54dd14d80bd5f777184cb9c8%26%2341%3B"));`

喜欢:
    $monitorname = $_GET["monitorname"]; $monitorname = html_entity_decode(urldecode($monitorname)); //CODE preg_match('/\(([^)]+)\)/', $monitorname, $match); $id = $match[1]; echo $id;

更多信息: PHP MANUAL - URLDECODE
PHP MANUAL - HTML_ENTITY_DECODE

已更新!

答案 1 :(得分:0)

$monitorname = $_GET['monitorname'];
$src=array('(',')');
$rep=array('(',')');
$monitorname=str_replace($src,$rep,$monitorname);

//now your code

preg_match('/\(([^)]+)\)/', $monitorname, $match);
$id = $match[1];
echo $id;

我的第一个想法是urldecode(),但在这种情况下它不起作用......