将所有出现的给定字符串替换为字符串中的匹配记录

我的问题是:我有一个字符串。此字符串中的ID位于两个%字符内。对于每个ID,多维数组中都有匹配的记录。数组键是两个%字符之间的ID。对于字符串中的每次出现,我想用相应的记录替换ID和2%字符。

字符串链示例:

Lorem %1% dolor sit amet,consetetur sadipscing elitr,sed diam %5% eirmod tempor invidunt ut labore et dolore %7% aliquyam erat,sed diam voluptua.

包含用户数据的数组示例:

Array ( [0] => Array ( [id] => 0 [data] => LOREM ) [1] => Array ( [id] => 1 [data] => IPSUM ) ) 

我已经尝试使用explode将整个字符串链转换为数组,然后使用foreach循环遍历数组项。不幸的是,字符串中的空格导致了我的问题,因此爆炸无法正常工作,而且我无法在自己的数组条目中获得所有单词。

到目前为止,我有一个函数“ getcontents()”,通过它我可以从整个字符串链中获得所有出现的2%字符以及ID。我使用ID从数据库中提取相应的记录,并将它们存储在数组中。

  function getcontents($str,$startDelimiter = '%',$endDelimiter = '%') {

    $contents = array();
    $startDelimiterLength = strlen($startDelimiter);
    $endDelimiterLength = strlen($endDelimiter);
    $startFrom = $contentStart = $contentEnd = 0;

    while (false !== ($contentStart = strpos($str,$startDelimiter,$startFrom))) {

      $contentStart += $startDelimiterLength;
      $contentEnd = strpos($str,$endDelimiter,$contentStart);

      if (false === $contentEnd) {
        break;
      }

      $contents[] = substr($str,$contentStart,$contentEnd - $contentStart);
      $startFrom = $contentEnd + $endDelimiterLength;

    }

    return $contents;

  }

  function getUserDataFields($input,$userid)
  {

    $dataFields = $this->getcontents($input);

    foreach($dataFields as $key => $field){
      $datas[$key] = ["id" => $key,"data" => $this->userController->getcustomerDataByFieldId($userid,$field)];
    }


//At this point I want to loop through the whole string chain in some way to replace All Ids with the corresponding separators with the matching records and then return the whole string from the function.

  }

sibi333 回答:将所有出现的给定字符串替换为字符串中的匹配记录

您可以在此处传递数组,字符串和定界符包装器,如果在数组中找到它,则它将替换它;否则别管它。

$str = 'Lorem %1% dolor sit amet,consetetur sadipscing elitr,sed diam %0% eirmod tempor invidunt ut labore et dolore %7% aliquyam erat,sed diam voluptua.';

$arr = [
  [
    'id' => 0,'data' => 'LOREM'
  ],[
    'id' => 1,'data' => 'IPSUM'
  ]
];

$newStr = replaceContent($arr,$str);

echo $newStr;

function replaceContent($arr,$str,$startDelimiter = '%',$endDelimiter = '%') {
  preg_match_all("#{$startDelimiter}([\d]+){$endDelimiter}#",$matches);

  foreach($matches[1] as $key => $value) {
    $index = array_search($value,array_column($arr,'id'));
    if ($index === false) continue;

    $str = str_replace($matches[0][$key],$arr[$index]['data'],$str);
  }

  return $str;
}
,

您可以提取由id索引的数组,然后使用找到的数字进行替换:

$array = array_column($array,'data','id');
$text = preg_replace_callback('/%(\d+)%/',function ($m) use($array) {
                                               return $array[$m[1]];
                                           },$text);

或者只是使用这些索引的简单循环:

foreach(array_column($array,'id') as $key => $val) {
    $text = str_replace("%$key%",$val,$text);
}
本文链接:https://www.f2er.com/3158816.html

大家都在问