0
votes

How can I make this filter work on multiple matches within the same text?

function _embed_link($text, $filter, $format) {
  if (preg_match_all("/\[(.*?)\|(node|term)\:(\d+)\]/i", $text, $params)) {
    foreach ($params[0] as $key => $param) {
      $args = array(
        $params[0][$key],
        $params[1][$key],
        $params[2][$key],
        $params[3][$key],
      );
      $markup = _embed_link_process($args);
      $text = preg_replace("/\[(.*?)\|(node|term)\:(\d+)\]/", $markup, $text, 1);
    }
  }

  return $text;
}

and this is the function which returns the link

function _embed_link_process($params = array()) {
  $output = '';

  if ($params[2] == 'node') {
    // Find node by it's id
    $node = node_load($params[3]);
    $output .= render(l($params[1], 'node/'. $node->nid, array(
      'attributes' => array(
        'class' => array('embed-link', 'embed-link-node', 'embed-link-node-'. $node->nid),
      ),
    )));
  }

  if ($params[2] == 'term') {
    $term = taxonomy_term_load($params[3]);;
    $output .= render(l($params[1], 'taxonomy/term/'. $term->tid, array(
      'attributes' => array(
        'class' => array('embed-link', 'embed-link-term', 'embed-link-term-'. $term->tid),
      ),
    )));
  }

  return $output;
}

Example text using the filter:

Ut [Click here|node:4] enim ad minim veniam, quis [Click here|term:42] nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum [Click here|term:1] dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa [Click here|node:42] qui officia deserunt mollit anim id est laborum.

The goal is to have each [...] replaced by the proper link.

2

2 Answers

0
votes

See the documentation of preg_replace.

The last parameter (1) explicitly says that you want to replace only the first occurrence. Remove it and all occurrences should be replaced.

0
votes

Modifying function _embed_link to use preg_match_all

function _embed_link($text, $filter, $format) {
  if (preg_match_all("/\[(.*?)\|(node|term)\:(\d+)\]/i", $text, $params)) {
    foreach ($params[0] as $key => $param) {
      // $param => [Click here|node:4]
      $param_arr  = array (
        $params[0][$key], // [Click here|node:4]
        $params[1][$key], // Click here
        $params[2][$key], // node
        $params[3][$key], // 4
      );
      $markup = _embed_link_process($param_arr);
      $text = str_replace($param, $markup, $text);
    }
  }

  return $text;
}