【问题标题】:Scraping text from string从字符串中抓取文本
【发布时间】:2023-03-23 16:48:01
【问题描述】:

如果不清楚,请见谅(我是 php 的初学者)。

假设我有一个字符串,我抓取了 $results,我想进一步抓取它的信息并将其分配给变量。传入的信息每次都会变化。

$results 的一个例子是:

Array ( [name] => Tennismix2 [count] => 1 [frequency] => On demand [version] => 9 [newdata] => 1 [lastrunstatus] => success [thisversionrun] => Wed Nov 12 2014 08:54:58 GMT+0000 (UTC) [lastsuccess] => Wed Nov 05 2014 08:28:44 GMT+0000 (UTC) [results] => Array ( [collection1] => Array ( [0] => Array ( [Bondsnummer] => 21169152 [Naam] => Baal, A.J.W. van [Geslacht] => M [Spelersterkte Enkel] => 4 [Spelersterkte Dubbel] => 4 ) ) ) )

我想从这个字符串中提取 5 件事:-“Bondsnummer”后面的 8 位数字,“Naam”后面的名字(显然长度不同),“Geslacht”后面的性别,后面的数字“Enkel”,以及“Dubbel”背后的数字

我尝试过使用这样的子字符串:

$bondsnummer = substr($response, 326, 8);

但是当名称的长度使初始字符串变长或变短时,我会遇到麻烦。

有没有更聪明/更好的方法从这样的字符串中抓取?

【问题讨论】:

  • 这是一个print_r() 转储,你为什么要解析它?直接将它指向你想在数组中获取的索引
  • 指向索引,如echo $results['name']; 它将显示名称。

标签: php string web-scraping


【解决方案1】:

尝试查看 Regex(正则表达式),看看这是否可以解决您的问题:

这是一个示例教程:

http://php.net/manual/en/function.preg-match.php

【讨论】:

    【解决方案2】:

    获取您可以直接访问的 8 位数字:

    $response['results']['collection1'][0]['Bondsnummer']
    

    姓名:

    $response['results']['collection1'][0]['naam']  // and so on...
    

    【讨论】:

    • echo $response['results']['collection1'][0]['Bondsnummer'];给我这个:警告:第 9 行 C:\xampp\htdocs\test\kimonobondsnummer.php 中的非法字符串偏移 'results' 警告:C:\xampp\htdocs\test\kimonobondsnummer.php 中的非法字符串偏移 'collection1'第 9 行警告:第 9 行 C:\xampp\htdocs\test\kimonobondsnummer.php 中的非法字符串偏移 'Bondsnummer' {
    • 试试 echo '
      ';print_r($response);echo '
      ';然后粘贴输出。然后将清除偏移以检索值
    猜你喜欢
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    相关资源
    最近更新 更多