protected function AlinkPostRenderer::replaceFirst in Alinks 8
Uses regular expression to replace the first matched keyword in content.
2 calls to AlinkPostRenderer::replaceFirst()
- AlinkPostRenderer::processDomNodeList in src/
AlinkPostRenderer.php  - Process the node list to replace links.
 - AlinkPostRenderer::replace in src/
AlinkPostRenderer.php  - Load the content and replace the matched strings with automatic links.
 
File
- src/
AlinkPostRenderer.php, line 186  
Class
- AlinkPostRenderer
 - Class AlinkPostRenderer.
 
Namespace
Drupal\alinksCode
protected function replaceFirst(Keyword $search, $replace, $subject, &$count = 0) {
  $search_escaped = preg_quote($search
    ->getText(), '/');
  $subject = preg_replace('/\\b' . $search_escaped . '\\b/u', $replace, $subject, 1, $count);
  if ($count == 0) {
    // @TODO: Look at Search API Tokenizer & Highlighter
    $terms = str_replace([
      '.',
      ',',
      ';',
      '!',
      '?',
    ], '', $subject);
    $terms = explode(' ', $terms);
    $terms = array_filter(array_map('trim', $terms));
    $terms = array_combine($terms, $terms);
    $terms = array_map(function ($term) {
      if (!isset($this->stemmerCache[$term])) {
        $this->stemmerCache[$term] = $this->stemmer
          ->stem($term);
      }
      return $this->stemmerCache[$term];
    }, $terms);
    foreach ($terms as $original_term => $term) {
      if ($term === $search->stemmed_keyword) {
        $search_escaped = preg_quote($original_term, '/');
        $subject = preg_replace('/\\b' . $search_escaped . '\\b/u', '<a href="' . $search
          ->getUrl() . '">' . $original_term . '</a>', $subject, 1, $count);
      }
    }
  }
  return $subject;
}