【问题标题】:How can I extract some parts of a PHP string that are separated by spaces如何提取由空格分隔的 PHP 字符串的某些部分
【发布时间】:2014-11-21 11:44:15
【问题描述】:

我的 PHP 字符串如下所示:

$test1= '   1    AAA vs SSS    ';
$test2= '  2        GGG vs FFF ';

我需要从字符串中提取 NUMBER 和名称:

[0] => stdClass Object
    (
        [no] => 1
        [one] => AAA 
        [two] => SSS    
    )

我该怎么做?

【问题讨论】:

  • 什么是数组,想要的输出?
  • 正则表达式是一个很好的起点。到目前为止,您尝试了什么?

标签: php regex string str-replace explode


【解决方案1】:
^(\s| )*([0-9:]+)\s+(\S.*\S)\svs\s(\S.*\S)\s*$

在替换中,时间将以 $1 为单位 主队 2 美元 3美元的客队 (第三场比赛比分0-3)

Demo here

在您的 PHP 文件中:

$game1 = ' 04:60    FC Heidenheim 1846 vs SV Sandhausen    ';
//I strip the  's first to have a simpler regexp
$game1 = str_replace(' ',' ',$game1);
preg_match ("@^\s*([0-9:]+)\s+(\S.*\S)\svs\s(\S.*\S)\s*$@", $game1, $matches); 
$result =new stdClass;
$result->time = $matches[1];
$result->hometeam = $matches[2];
$result->awayteam = $matches[3];

var_dump( $result );

【讨论】:

  • 使用 preg_match() : preg_match ("@^\s*([0-9]{2}:[0-9]{2})\s+(\S.*\S) \svs\s(\S.*\S)\s*$@", $game1, $matches);回声 $matches[1]。' '.$matches[2].' - '.$matches[3];
  • 如果答案如你所愿,别忘了接受 ;)
  • 是的,但它不适用于这种情况:  1 AAA 与 SSS
  • 您的问题最初是“11:11 A A A vs S SS”;)
  • 原来的消息中没有,因为它被隐藏了,我不知道我有一个nbsp,我以为它是一个空格
【解决方案2】:

你应该在你的字符串上使用 trim(), 如果结构字符串没有改变,则在它之后:

$game = trim($game);

$hour = substr($game,0,5);

$opponents = substr($game, 6);

$opponents = explode("vs",$opponents);

所以数组看起来

array(
'hour'=>$hour,
'home_team'=>$opponents[0],
'away_team'=>$opponents[1] );

我没有测试它,但它看起来像这样

【讨论】:

    【解决方案3】:

    我不懂 PHP,但您可以使用下面的正则表达式来获取值。 group 1 有时间,group 2 有主队名称,group 3 有客队名称。

    ^([\d:]+)\s+([\w\s\d]+)\s+vs\s+([\w\s\d]+)\s?$
    

    Here you can see the regex demo.

    【讨论】:

      【解决方案4】:

      你可以试试,

      $test1= ' 1    AAA vs SSS    ';
      $test2= '  2        GGG vs FFF ';
      
      $test1 = dataFormatter($test1);
      $test2 = dataFormatter($test2);
      
      print_r($test1);
      print_r($test2);
      
      function dataFormatter($data)
      {
          $data= explode(" ",$data);
          foreach($data as $value)
          {
              if($value && $value!= vs)
                  $newData[] = $value;
          }
          return $newData;
      }
      

      输出:

      Array
      (
      [0] => 1
      [1] => AAA
      [2] => SSS
      )
      
      Array
      (
      [0] => 2
      [1] => GGG
      [2] => FFF
      )
      

      【讨论】:

        猜你喜欢
        • 2017-12-25
        • 1970-01-01
        • 2022-01-02
        • 1970-01-01
        • 2017-08-30
        • 1970-01-01
        • 2016-07-15
        • 1970-01-01
        • 2022-11-13
        相关资源
        最近更新 更多