【问题标题】:PHP: Making quotes on every word in stringPHP:在字符串中的每个单词上加上引号
【发布时间】:2016-03-10 20:44:36
【问题描述】:

PHP 初学者,看起来很有趣。我已经设法将逗号和“=>”放在我需要的任何地方,但我也需要在每个单词周围加上引号。我无法理解如何管理这部分。

我正在尝试使用字符串中的键和值构建一个不错的数组。

这是字符串的开头

$dummy = "ac whois.nic.ac 
          ae whois.aeda.net.ae 
          aero whois.aero 
          af whois.nic.af 
          ag whois.nic.ag 
          ...."

我需要的是

"ac" => "whois.nic.ac", 
"ae" => "whois.aeda.net.ae", 
"aero" => "whois.aero", 
"af" => "whois.nic.af", 
"ag" => "whois.nic.ag", 

到目前为止我已经得到了什么......

ac => whois.nic.ac, 
ae => whois.aeda.net.ae, 
aero => whois.aero, 
af => whois.nic.af, 
ag => whois.nic.ag, 

在每个“/n”上创建一个逗号

$strg = preg_replace("/(?<![.])(?=[\n\r]|$)/", ",", $dummy);

在每个空间上创建“=>”

$strg = str_replace(' ', ' => ', $strg);

干杯..

【问题讨论】:

    标签: php arrays string preg-replace str-replace


    【解决方案1】:

    我会在不使用 preg_replace 的情况下这样做:

    $dummy = "ac whois.nic.ac 
          ae whois.aeda.net.ae 
          aero whois.aero 
          af whois.nic.af 
          ag whois.nic.ag 
          ....";
    $lines = preg_split('[\r\n]+', $dummy, null, PREG_SPLIT_NO_EMPTY);
    $lines = array_filter(array_map(function($line){
        $line = trim($line);
        $words = explode(" ", $line, 2);
        if(count($words) !== 2) return null;
        return "\"$words[0]\" => \"$words[1]\",";
    }));
    $output = implode("\n", $lines); // or whatever EOL it was
    

    【讨论】:

      猜你喜欢
      • 2018-11-28
      • 1970-01-01
      • 2016-12-26
      • 1970-01-01
      • 2011-01-13
      • 1970-01-01
      • 2015-11-09
      • 2017-07-25
      相关资源
      最近更新 更多