【问题标题】:PHP: How to use preg_match() here?PHP:如何在这里使用 preg_match()?
【发布时间】:2017-06-13 21:46:33
【问题描述】:

我有两个类似的字符串

stdClass Object ( [id] => 10303 )

 stdClass Object ( [error] => not found )

如何通过preg_match() 函数捕获iderror?我用过这段代码,但没有帮助:

$file = 'stdClass Object ( [id] => 10303 )';
preg_match('/\[id\] \=\> ([0-9]+)/', $file, $mfc);
var_dump($mfc);

【问题讨论】:

  • 你怎么会有这样的字符串?如果您真的在变量中有这样的字符串,那么这些显然是以某种方式被转换的对象。检查它是如何产生的不是很有意义吗?因为从这样的字符串中解析一些消息听起来像是一个非常糟糕的解决方法......
  • 那些看起来像对象。你有没有想过这样使用它们?或者你真的坚持使用字符串?另外,检查匹配或捕获值,如“10303”?
  • “它没有帮助”是什么意思?当我尝试您的代码时,它似乎按预期工作......那么您的实际问题是什么?
  • 我正在尝试一些 api 并且他们的响应非常混乱,我要求他们修复他们的响应但他们没有。现在我想捕获 id 和错误。或者告诉我如何解析这些对象字符串以再次将它们转换为数组或对象...

标签: php arrays string preg-match preg-match-all


【解决方案1】:

error你可以用这个!

preg_match('/\[error\][\s]*\=\>[\s]*(.*?)\?/', $file, $mfc);
var_dump($mfc);

对于ID

$syntax = '/\[id\][\s]*\=\>[\s]*([0-9]+)/';
preg_match($syntax, $file, $mfc);
var_dump($mfc);

【讨论】:

    【解决方案2】:

    身份证

    preg_match('/\[id\][\s]*\=\>[\s]*([0-9]+)/', $file, $mfc);
    

    错误文本

    preg_match('/\[error\][\s]*\=\>[\s]*(.*?)\?/', $file, $mfc);
    

    您的正则表达式的主要变化是考虑到任何前所未有的空白字符。

    【讨论】:

      猜你喜欢
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多