Skip to content

What's the best way change link innertext? #817

Answered by colinodell
benfiratkaya asked this question in Q&A
Discussion options

You must be logged in to vote

That looks pretty good to me! If you wanted to optimize this further you could do something like this:

// Avoid iterating through the entire document if we already know we won't be doing anything
if ($link_type === self::APPLY_NONE)
  return;

foreach ($e->getDocument()->iterator() as $link) {
  if (!($link instanceof Link))
    continue;
  
  $host = parse_url($link->getUrl(), PHP_URL_HOST);
  if (!is_string($host)) {
    // Something is terribly wrong with this URL
    continue;
  }
  
  // This does exactly the same thing you did under-the-hood.  It isn't any faster or better, but it might be easier to understand:
  $link->replaceChildren([new Text($link->getUrl())]);
}

Nicely done!

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by benfiratkaya
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants