【问题标题】:Get a substring of a string获取字符串的子字符串
【发布时间】:2015-07-07 05:12:07
【问题描述】:

我一直在尝试获取包含大约 40 行文本的字符串的子字符串。

字符串是这样的,但带有 aprox.还有 30 行:

Username: example
Password: pswd
Code: 890382
Key: 9082
type: 1
Website: https://example.com/example
Email: example@example.com

我需要获取例如Code 的值,这将是890382,但我似乎做不到。

CodeKey 这样的每个字段在字符串中都是唯一的。最好的(如果可能的话)是读取值并将它们存储在以字段命名的位置的数组中。如果有人可以帮助我,我将不胜感激。

顺便说一句:这个文件托管在不同的服务器上,我只能读取它,所以我不能把它改成更像 CSV 的东西。

我尝试使用的代码:

$begin=strpos($output, 'Code: ');
$end=strpos($output, '<br>', $begin);

$sub=substr($output, $begin, $end);
echo $sub;

【问题讨论】:

  • 你试过了吗?
  • 当然!我尝试使用 strpos 将字符串作为 haystack 并将字段名称作为 needle 以获取子字符串的开头,然后我尝试使用相同的东西,但使用 strpos 的先前结果作为开头,并且 和针得到结束位置。之后我尝试使用 substr 来获取使用开始和结束位置的子字符串。它没有用...(顺便说一句,我使用 nl2br 将 \n 转换为
  • ^ 然后向我们展示您的工作和尝试!显示您的代码。
  • 您所在的国家/地区有 google 吗? stackoverflow.com/questions/5752594/…
  • @user3676792 只需edit您的问题并添加您的代码

标签: php string substring substr strpos


【解决方案1】:

分割每一行,然后在冒号处分割。并将密钥/对放入数组中:

$string = "..."; // your string
$lines = explode("\n",str_replace("\r","\n",$string)); // all forms of new lines
foreach ($lines as $line) {
    $pieces = explode(":", $line, 2); // allows the extra colon URLs
    if (count($pieces) == 2) { // skip empty and malformed lines
        $values[trim($pieces[0])] = trim($pieces[1]); // puts keys and values in array
    }
}

现在您可以通过访问$values['Code']获得您的价值

【讨论】:

  • 完美!经过一些调整后做了我想要的一切。谢谢
【解决方案2】:

这应该适合你:

这里我先explode()你的字符串换一个换行符。在此之后,我使用array_map() 遍历每个元素,并通过: 再次对其进行分解。然后我只需array_combine() 第一个数组列和第二个列,我用array_column() 得到。

<?php

    $str = "Username: example
            Password: pswd
            Code: 890382
            Key: 9082
            type: 1
            Website: https://example.com/example
            Email: example@example.com";

    $arr = array_map(function($v){
        return array_map("trim", explode(":", $v, 2));
    }, explode(PHP_EOL, $str));

    $arr = array_combine(array_column($arr, 0), array_column($arr, 1));

    print_r($arr);

?>

输出:

Array
(
    [Username] => example
    [Password] => pswd
    [Code] => 890382
    [Key] => 9082
    [type] => 1
    [Website] => https://example.com/example
    [Email] => example@example.com
)

【讨论】:

    【解决方案3】:

    取用户名的结束位置:然后找到密码的开始位置。然后使用这些值来提取用户名值。像这样找到你想要的值...

    【讨论】:

      【解决方案4】:

      假设你的字符串用换行符分隔,你可以试试这个:

      $str = "Username: example
      
              Password: pswd
      
              Code: 890382
      
              Key: 9082
      
             type: 1
      
             Website: https://example.com/example
      
             Email: example@example.com";
      
      $explode = explode("<br/>", $str);
      foreach ($explode as $string) {
           $nextExplode = explode(":", $str);
               foreach($nextExplode as $nextString) {
                   if ($nextString[0] == 'Code']) {
                       echo $nextString[1];
                   }
                }
           }
      

      【讨论】:

      • 如果使用
        无法分解,用户可以使用 str_replace 函数将所有换行符转换为空格。然后可以使用针作为空格通过explode函数进行。不是吗?
      • 此代码将永远无法工作。首先,字符串中没有&lt;br/&gt;。它不是html。其次,你正在爆炸,并foreaching一个字符串,然后取出一块并将其视为一个数组。
      【解决方案5】:

      你可以试试

      preg_match('/Code: ([0-9]+)/', $subject, $matches);
      

      您应该在 $matches 数组中有代码。

      您应该调整正则表达式,使其适合您的情况。我只是举个例子。

      【讨论】:

        【解决方案6】:

        在您的特殊情况下使用以下代码:

        preg_match('/Code\:\s*(.*)\s*/m', $yourstring, $match); 
        $match[1] //contains your code! 
        

        【讨论】:

          【解决方案7】:

          尝试使用拆分分隔符 "\n" 和/或 ':' 这将为您提供一个数组,您可以在其中进一步分解为键值对。

          在下面的例子中,我采用了从文件中读取的方法,并在给定的一行中用“:\s”分割。

          即。以“data.txt”为例

          <?php
          
          $results = array();
          
          $file_handle = fopen("data.txt", "r");
          while (!feof($file_handle)) {
             $line = fgets($file_handle);
             $line_array = preg_split("/:\s/", $line);
          
             // validations ommited 
             $key = $line_array[0];
             $value = $line_array[1];
          
             // ie. $result['Code'] => '890382' 
             $result[$key] = $value;
          }
          fclose($file_handle);
          
          print_r($result);
          
          ?>
          

          输出用法 ie.echo $result['Username']:

          Array
          (
              [Username] => example
          
              [Password] => pswd
          
              [Code] => 890382
          
              [Key] => 9082
          
              [type] => 1
          
              [Website] => https://example.com/example
          
              [Email] => example@example.com
          )
          

          【讨论】:

            猜你喜欢
            • 2011-12-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-08-21
            • 1970-01-01
            • 2014-12-13
            • 2017-10-16
            相关资源
            最近更新 更多