【问题标题】:PHP - Regular Expressions with Double Quoted StringsPHP - 带有双引号字符串的正则表达式
【发布时间】:2016-07-29 23:55:37
【问题描述】:

我正在尝试使用正则表达式从字符串中提取某个值:

"exec_hash": "/TPPE2ChB+5HuSHs84FBgx5/EgWi0OlaEXoXq4pq3Aukhc1Ypf0mZfKCJ10w=", "events_collector": "thiiM0ahsieSiech1phithe6chahngoo8sah6aid\n"

我想要的数据是引号之间的哈希。问题是字符串中有多个引号,preg_match_all 函数没有返回正确的数据。我一直在玩正则表达式,但无法弄清楚。最终,我希望将这些数据返回为一个值。例如:$string1 = '/TPPE2ChB+5HuSHs84FBgx5/EgWi0OlaEXoXq4pq3Aukhc1Ypf0mZfKCJ10w=';

更正:我正在使用 curl 来获取页面内容。数据不存储在变量中。

$matches = 数组(); $thing = preg_match_all('/hash": "(.*?)", "events/',$page,$matches); print_r($matches);

它会吐出一个长长的数组,而不仅仅是散列

【问题讨论】:

  • 向我们展示您的正则表达式模式如何?
  • 您的字符串来自 json 对象的任何更改?您的字符串将始终采用该格式?你能做这样的事情吗:tehplayground.com/#zPm65aO2r
  • $matches = array(); $thing = preg_match_all('/hash": "(.*?)", "events/',$page,$matches); print_r($matches);它吐出一长串不仅仅是散列

标签: php regex preg-match-all double-quotes


【解决方案1】:

感谢您的建议。

我想通了。我错过了表达式中的转义分隔符。

preg_match_all("/exec_hash\": \"(.*?)\", /",$page,$matches);

【讨论】:

    【解决方案2】:

    看起来是 json_decodable:

    //Get the result from curl request:
    $curlResult = '"exec_hash": "/TPPE2ChB+5HuSHs84FBgx5/EgWi0OlaEXoXq4pq3Aukhc1Ypf0mZfKCJ10w=", "events_collector": "thiiM0ahsieSiech1phithe6chahngoo8sah6aid\n"';
    
    //Parse the result:
    $parsedResult = json_decode($curlResult, true);
    //Get the hash:
    $hash = $parsedResult["exec_hash"];
    

    【讨论】:

    • 感谢您的回复。如果哈希值每 24 小时不断变化,这会起作用吗?
    • 嗨,验证这种方法非常重要的是确保 curl 返回的内容。如果保证内容可以用json_decode 解码,并且保证exec_hash 键一直这样命名,那么是的,这个脚本将一直有效。
    【解决方案3】:

    你可以使用 substr 吗?

    尚未对此进行测试,但理论上...

    $pos_of_comma = strpos($str, ",");
    if($pos_of_comma !== false) {
        $execHash = substr($str, 14, $pos_of_comma - 14);
    }
    

    【讨论】:

    • 或者你也可以在位置 14 之后获取双引号的下一个位置,这是 exec_hash 字符串的开始位置。
    • 我可以使用 preg_match_all 来捕获 _hash": " & ", "events_collector" 之间的所有内容吗?
    猜你喜欢
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多