Preg replace in textarea links

Asked

Viewed 52 times

-4

What can I do to play these link on textarea

Ex:

http://link1.com/embed/código/nomepagina 
http://link2.com/v/código/nomepagina 
http://link3.com/e/código/

And he returns me only

http://link1.com/código/ 
http://link2.com/código/ 
http://link3.com/código/

Taking the code only and formatting leaving the way up.

  • Rogério Want to skip a line in the textarea is this ? or want to change the format ?

  • The links when it is generated, is formed in the way of the first example, I wanted to be able to format these 3 links and leave the way of the second, take the CODE part of each link and the link1 part,Link2,link3

  • 3

    Do not duplicate your questions. If the previous was not well received, focus your efforts there. Edit it to stay within the scope, read more on [help/on-topic] and on the page [Ask]

1 answer

1


I created this regex that meets in this case you made:

(http:\/\/\w+\.\w+\/)(\w+)\/(\w+)\/(.+)?

 ^ .... grupo do link        ^.... grupo do código

Then take the elements of each group that will be used and join.

Would that be the code:

$str = "http://link1.com/embed/codigo/nomepagina 
        http://link2.com/v/codigo/nomepagina 
        http://link3.com/e/codigo/";

$str = preg_replace('/(http:\/\/\w+\.\w+\/)(\w+)\/(\w+)\/(.+)?/', '$1$3 ', $str);
                  //                                              ^ aqui haverá a junção

Exit:

http://link1.com/codigo http://link2.com/codigo http://link3.com/codigo

As it is a url I removed from código the accent on the ó

Editing

For subdomains and other types of domains I made the code like this:

$str = preg_replace('/(http:\/\/|https:\/\/)?([\w\.]+\/)([\w-_]+\/)?([\w-_]+)\/?(.+)?/', '$2$4 ', $str);
  • It worked so far, but what if some links have Ubdomain and others not? how would it work? type the first two for Ubdomain.link1.com/embed/code/... and the others without ?

  • @Rogériosilva I’ll do for subdominions

  • @Rogériosilva is there

  • @Rogériosilva worked out well?

  • 1

    yes thank you!!!

  • Andrei, do you know when the link has - (dash) does not catch? eg.com/embed/hB8l23wOU-E/ it returns only hB8l23wOU

  • @Rogériosilva I’ll make an issue

  • @Rogériosilva is there!

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.