将字符串转换为二维数组并改组

时间:2018-06-28 18:44:08

标签: php arrays wordpress advanced-custom-fields shortcode

我正在使用Wordpress和高级自定义字段。我的目标是从字段内部获取内容,并将其转换为二维数组,然后将其随机播放。内容是一系列短代码,看起来像[contentcards url =“ ...” options =“ ...”]

function shuffle_content_cards($content) {
  // $content = get_the_content();
  $short_codes = array();
  $the_short_code = '';
  $content = str_replace('<p>', '', $content);
  $content = str_replace('</p>', '', $content);
  if (strpos($content, ']') !== false ) {
  for ($i = 0; $i <= strlen($content); $i++) {
    if ($content[$i] == '[') {
      $start = $i;
    }
    else if ($content[$i] == ']') {
      $end = $i;
      $the_short_code = substr($content, $start, $end+1);
      $content = str_replace($the_short_code, ' ', $content );
      array_push($short_codes, $the_short_code);
// echo $the_short_code;
    }
  }
}
  shuffle($short_codes);
  $content = implode(' ', $short_codes);
  // echo $content;
  return $content;
}
add_filter('acf_the_content', 'shuffle_content_cards', 0);

我可以将其改组为数组并输出,唯一的问题是不显示最后一个短代码。内容中有7个短代码,最后一个在哪里都找不到。

这是var_dump($ short_codes);

的结果
array(3) { [0]=> string(169) "[contentcards url="https://www.gotimelinr.com/" custom_image="https://creativesfeed.com/wp-content/uploads/2018/06/timelinr-project-manager.jpg" custom_title="Timelinr"]" [1]=> string(549) " [contentcards url="https://ora.pm" custom_image="https://creativesfeed.com/wp-content/uploads/2018/06/ora-project-management-software.png" custom_title="Ora"] [contentcards url="https://monday.com/" custom_image="https://creativesfeed.com/wp-content/uploads/2018/06/monday-project-management.png" custom_title="Monday" custom_description="monday.com is a tool that simplify the way teams work together - Manage workload, track projects, move work forward, communicate with people - Adopt a management tool that people actually love to use."]" [2]=> string(703) " [contentcards url="https://www.outplanr.com/" custom_image="https://www.outplanr.com/img/screenshots/1.jpg" custom_title="Outplanr"] [contentcards url="https://hitask.com/" custom_image="https://creativesfeed.com/wp-content/uploads/2018/06/hitask-project-manager-software.jpg" custom_title="Hitask"] [contentcards url="https://freedcamp.com/" custom_image="https://creativesfeed.com/wp-content/uploads/2018/06/freedcamp-project-manager.jpg" custom_title="Freedcamp" custom_description="Our mission is to empower people to achieve great things together​. The notion of simple collaboration has been lost and split into hundreds of fragments with countless tools trying to solve each piece."]" }

0 个答案:

没有答案