Search code examples
phpregexpreg-replacepreg-match

PHP regex last occurrence of words


My string is: /var/www/domain.com/public_html/foo/bar/folder/another/..

I want to remove the root folder from this string, to get only public folder, because some servers have multiple websites inside.

My actual regex is: /^(.*?)(www|public_html|public|html)/s

My actual result is: /domain.com/public_html/foo/bar/folder/another/..

But i want to remove the last ocorrence, and get somethig like this: /foo/bar/folder/another/..

Thanks!


Solution

  • You have to use a greedy quantifier and to check if the alternative is enclosed between slashes using lookarounds:

    /^.*(?<![^\/])(?:www|public(?:_html)?|html)(?![^\/])/
    

    About the lookarounds: I use negative lookarounds with a negated character class to check if there is a slash or the limit of the string at the same time. This way you are sure that for instance html is a folder and not the part of another folder name.

    I removed the s modifier that is useless. I removed the capture groups too since the goal is to replace all with an empty string.