在 php 中拆分“xx: xxx yy: yyy”类型的字符串的方法


Way to split a "xx: xxx yy: yyy" kind of string in php

在PHP中拆分以下字符串的方式是什么:

"dc: http://purl.org/dc/terms/ foaf: http://xmlns.com/foaf/0.1/"

到:

"dc: http://purl.org/dc/terms/"
"foaf: http://xmlns.com/foaf/0.1/"

,然后将<>添加到网址

"dc: <http://purl.org/dc/terms/>"
"foaf: <http://xmlns.com/foaf/0.1/>"  

我会做的

$tmp = explode(" ", $string);
echo "{$tmp[0]} <{$tmp[1]}>'n";
echo "{$tmp[2]} <{$tmp[3]}>'n";
如果您不知道键/值对

的长度,您可以使用循环并知道每 2 个项目形成一个键/值对。

这是一个适用于任意数量令牌的解决方案:

<?php
    $string = 'dc: http://purl.org/dc/terms/ foaf: http://xmlns.com/foaf/0.1/';
    $explode = explode(' ', $string);
    $lines = array();
    for ($i = 0; $i < count($explode); $i += 2) {
        $lines[] = $explode[$i] . ' <' . $explode[$i + 1] . '>';
    }
    $string = implode("'n", $lines);
    echo $string;
?>

输出:

dc: <http://purl.org/dc/terms/>
foaf: <http://xmlns.com/foaf/0.1/>

演示


正则表达式解决方案(将/([^ ]+) ([^ ]+) ?/替换为$1 <$2>'n):

<?php
    $string = 'dc: http://purl.org/dc/terms/ foaf: http://xmlns.com/foaf/0.1/';
    $string = preg_replace('/([^ ]+) ([^ ]+) ?/', "$1 <$2>'n", $string);
    echo $string;
?>

演示

正则表达式尸检:

  • ([^ ]+) - 与任何不是空格 1 到无限次的字符匹配的捕获组
  • [SPACE] - 文字空格字符
  • ([^ ]+) - 将任何不是空格 1 的字符匹配到无限次的捕获组
  • [SPACE]? - 可选的文本空格字符

这样的东西会起作用

<?php
$str="dc: http://purl.org/dc/terms/ foaf: http://xmlns.com/foaf/0.1/";
$str=explode("/ ",$str);
$str[0]=str_replace(': ',': <',$str[0]);
$str[1]=str_replace(': ',': <',$str[1]);
echo $str[0]=$str[0].'>'; //dc: <http://purl.org/dc/terms>
echo $str[1]=$str[1].'>'; //foaf: <http://xmlns.com/foaf/0.1/> 

您可以执行类似操作以使其尽可能简单:

$new_string = trim(preg_replace('~([a-z]+:'s)(.*?)('s|$)~', "[@@@]$1 <$2>", 
              $original_string), "[@@@]");

$original_string是输入字符串。只需将其爆炸即可获得数组。

$array = explode("[@@@]", $new_string);
print_r($array);

输出:

Array
(
    [0] => dc:  <http://purl.org/dc/terms/>
    [1] => foaf:  <http://xmlns.com/foaf/0.1/>
)