首页 > 解决方案 > 替换字符串数组中的所有字符串不起作用

问题描述

我有以下字符串

$content = '[tab title="Tab A" content="Tab a content."][tab title="Tab B" content="Tab B content"][tab title="Tab C" content="Tab C content"]';

现在我想像这样拆分内容:

$contentID = preg_split('/(\]\[)|(\]\s*\[)/', $content);

到目前为止一切顺利,现在我需要检查$contentID数组的每个字符串是否包含该id=部分,以便在缺少时添加它:

// set a new array
$newContentID = array();
// set a unique ID
$id = 'unique';

// include an id attribute for each string part
foreach ( $contentID as $i => $tabID ) {
 $newContentID[$i] = !strpos( $tabID, 'id=' ) === true ? str_replace( '[tab', '[tab id="'.$id.'-'.$i.'"', $tabID) : $tabID;
}

最后,我只是将所有内容内爆到同一个$content数组中。

$content = implode('][',$newContentID);

新的内容是#content这样的:

var_dump($content);

/////////////// RESULT ///////////////////
string "[tab id="unique-0" title="Tab A" content="Tab a content."][tab title="Tab B" content="Tab B content"][tab title="Tab C" content="Tab C content"]"


var_dump($contentID);

/////////////// RESULT ///////////////////

array(3) {
  [0]=>
  string(13) "
[tab id="tab-a" title="Tab A" active="1" content="Tab a content""
  [1]=>
  string(13) "tab id="tab-b" title="Tab B" content="Tab B content""
  [2]=>
  string(13) "tab id="tab-c" title="Tab C" content="Tab C content."]
"
}

为什么不做foreach我期望它做的事情(id在缺少的每个字符串部分中添加)?我该如何解决这个问题?

标签: phparraysforeachstr-replace

解决方案


id 部分没有被添加,因为结果preg_split是:

array(3) {
  [0]=>
  string(43) "[tab title="Tab A" content="Tab a content.""
  [1]=>
  string(41) "tab title="Tab B" content="Tab B content""
  [2]=>
  string(42) "tab title="Tab C" content="Tab C content"]"
}

这意味着str_replace('[tab', '[tab id="'.$id.'-'.$i.'"', $tabID)foreach 上的 将不起作用,因为对于数组索引 (1, 2) 没有[tab要替换的字符串。

一种解决方法是使用如下函数检查是否[tab存在strpos

$content = '[tab title="Tab A" content="Tab a content."][tab title="Tab B" content="Tab B content"][tab title="Tab C" content="Tab C content"]';

$contentID = preg_split('/(\]\[)|(\]\s*\[)/', $content);

// set a new array
$newContentID = array();
// set a unique ID
$id = 'unique';

// include an id attribute for each string part
foreach ( $contentID as $i => $tabID ) {
 $newContentID[$i] = strpos($tabID, 'id=') === false ? addId($tabID, $id, $i) : $tabID;
}

$content = implode('][',$newContentID);

function addId($tabID, $id, $i) {
    if (strpos($tabID, '[tab') === 0) {
        return str_replace('[tab', '[tab id="'.$id.'-'.$i.'"', $tabID);
    } else if (strpos($tabID, 'tab') === 0) {
        return 'tab id="' . $id . '-' . $i . '"' . substr($tabID, 3);
    }
}

结果echo $content

[tab id="unique-0" title="Tab A" content="Tab a content."][tab id="unique-1" title="Tab B" content="Tab B content"][tab id="unique-2" title="Tab C" content="Tab C content"]

推荐阅读