-1

I have in my string $content many url:

<a href="https://domain/wp-content/uploads/2018/07/sample-Wokal-2.jpg"><img class="alignright size-full wp-image-6608" src="https://domain/wp-content/uploads/2018/07/sample-Wokal-2.jpg" alt="sample Wokal 2" width="933" height="617" /></a>

<a href="https://domain/wp-content/uploads/2014/01/sample-lato-123.jpg"><img class="alignright size-full wp-image-6608" src="https://domain/uploads/2014/01/sample-lato-123.jpg" alt="sample lato 123" width="933" height="617" /></a>

etc

Is it possible replace all links to: - https://domain/files/sample-lato-123.jpg , - https://domain/files/sample-Wokal-2.jpg ,

etc?

How to do it? I tried str_replace - but I have different types of links and I do not know how to replace them. I do not know about regular expressions :(

Please help.

delifer
  • 35
  • 5
  • 1
    If `$content` is just HTML/XML then convert it to a DOM object and use XPath to target and modify links. – MonkeyZeus Dec 05 '18 at 16:07
  • I can not do this. Could you write me how to do it? – delifer Dec 05 '18 at 16:08
  • 4
    No. I believe in you. Read https://stackoverflow.com/a/1744154/2191572 to get started. If you have a specific issue then come back and ask for help. – MonkeyZeus Dec 05 '18 at 16:09
  • Not at all, you should use preg_match :and preg_replace – Shim-Sao Dec 05 '18 at 16:09
  • Forgive my bogus answer, i deleted it. If you really want to match URLs via regex, maybe this thread might help: https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url – bkis Dec 05 '18 at 16:18

1 Answers1

0

You can use this regex which does lookarounds to ensure the string that needs to be replaced is indeed the one we want,

(?<=domain).*?(?=sample)

and replace with

/files/

Here is sample PHP code,

$str = '<a href="https://domain/wp-content/uploads/2018/07/sample-Wokal-2.jpg"><img class="alignright size-full wp-image-6608" src="https://domain/wp-content/uploads/2018/07/sample-Wokal-2.jpg" alt="sample Wokal 2" width="933" height="617" /></a>\n<a href="https://domain/wp-content/uploads/2014/01/sample-lato-123.jpg"><img class="alignright size-full wp-image-6608" src="https://domain/uploads/2014/01/sample-lato-123.jpg" alt="sample lato 123" width="933" height="617" /></a>';
echo preg_replace('/(?<=domain).*?(?=sample)/', '/files/', $str);

Prints,

<a href="https://domain/files/sample-Wokal-2.jpg"><img class="alignright size-full wp-image-6608" src="https://domain/files/sample-Wokal-2.jpg" alt="sample Wokal 2" width="933" height="617" /></a>\n<a href="https://domain/files/sample-lato-123.jpg"><img class="alignright size-full wp-image-6608" src="https://domain/files/sample-lato-123.jpg" alt="sample lato 123" width="933" height="617" /></a>

Let me know if this works fine for you.

Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36