0

In my website, I'm using get_the_content() to display the contents of my posts. But, my post video URL, which is youtube here, also getting displayed along with my content.

I tried using preg_replace() to avoid the string that has the youtube URL. But I want to do it dynamically, by using beginning of the string 'https://www.youtube.com/watch?v' to replace it with empty string.

I'm exactly looking for something like this. $description = preg_replace('https://www.youtube.com/watch?v=f0cReHKUiJM', '', get_the_content());

Please share your ideas on how can I accomplish this.

Thanks in advance.

1 Answers1

0

If you literally want to remove all youtube urls from your get_the_content() string, (assuming the href value is double quoted) you can use this:

~https?:/{2}(?:w{3}\.)?youtube\.com[^"]+~

Pattern Demo

This can be implemented as:

$description=preg_replace('~https?:/{2}(?:w{3}\.)?youtube\.com[^"]+~','',get_the_content());

PHP Demo

But this will leave the "shell" of the link (<a href="">...</a>).


You could go one step further and remove tags and retain the text within:

~<a.*?href="https?://(?:www\.)?youtube\.com[^>]*>(.*?)</a>~

Pattern Demo

Implementation:

$description=preg_replace('~<a.*?https?://(?:www\.)?youtube\.com[^>]*>(.*?)</a>~','\1',get_the_content());

PHP Demo

The truth is, you haven't provided any full string samples from get_the_content() or explained if there were variations in the url or a tag structure (extra attributes or manner of quoting). These factors will likely impact the pattern design. My answer is mostly based on assumptions. Maybe it will help you. If it doesn't, it would be best if you updated your question.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • This string won't have youtube.com Sometimes it's an embedded URL. – Vijay Bhaskar Kavarthapu Nov 14 '17 at 11:23
  • I understand the "needle" that you are trying to match. Can you offer me a realistic "haystack"? (Or two of them) I will be able to help you if I understand the full story. Please show me how much the haystacks may vary and what doesn't work as expected with my answer. – mickmackusa Nov 14 '17 at 11:28
  • Please supply my requested information so that I can resolve this page. – mickmackusa Nov 15 '17 at 14:45