Benn
Benn

Reputation: 5023

Ho to use preg_match_all to find a string that has specific beging and specific end?-PHP

I am using this regex on css file to find all font-face fonts and to add missing full path to the font string.

    if(preg_match_all("/(url\('(.*?)'\))/s", $readcssfile, $fontstrings)){

        $fontstrings[1] = str_replace("('", "('newpath/", $fontstrings[1]);

        print_r($fontstrings[1]);
    }

this is the return .

Array
(
    [0] => url('newpath/../fonts/glyphicons-halflings-regular.eot')
    [1] => url('newpath/../fonts/glyphicons-halflings-regular.eot?#iefix')
    [2] => url('newpath/../fonts/glyphicons-halflings-regular.woff')
    [3] => url('newpath/../fonts/glyphicons-halflings-regular.ttf')
    [4] => url('newpath/../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular')
    [5] => url('newpath/PTN77F-webfont.eot')
    [6] => url('newpath/PTN77F-webfont.eot?#iefix')
    [7] => url('newpath/PTN77F-webfont.woff')
    [8] => url('newpath/PTN77F-webfont.ttf')
    [9] => url('newpath/PTN77F-webfont.svg#PTSansNarrowBold')
)

What I am actually looking for are those that have no relative path

url('PTN77F ...

But as you can see I found all fonts. I must be very specific so I would not make any mistakes , I need to match all

eot|#iefix|woff|ttf|svg, 

that do not have relative paths like , ../ or ..anything

and change their path to new path.

The thing is as soon as I add something like this in regex

preg_match_all("/(url\('(.*?).eot'\))/s", $readcssfile, $fontstrings)

I end up with array that has complete stylesheet in it.

I cannot search by actual font name since I will never know what it will be.

So how to I match only the ones that dont have relative path and how to find fonts with specific extension?

Any help is appreciated.

Upvotes: 0

Views: 71

Answers (2)

tenub
tenub

Reputation: 3446

First assert that there is no relative path by making sure no ../ exists on the line:

(?!.*\.\.\/)

Then modify the above expression to grab the actual URL into a capture group:

^(?!.*\.\.\/)url\('?(.*?)'?\)$

And then for each match there will be an array element [1] with the captured URL and [0] will be the full match.

Note: this should be done so that ^ / $ match per line, so ensure the m flag is not set.

Upvotes: 1

Benn
Benn

Reputation: 5023

It was much easier than I thought by referencing this here

https://stackoverflow.com/a/406408/594423

I end up matching only the ones that have nothing before ('

and replacing them

preg_replace("/(url\('(?!\.)(?!\/))/s","url('newpath/", $readcssfile);

it is kinda what tenub referenced in the fist line

Upvotes: 0

Related Questions