0

I would like to find fileName with extension in the text using regular expression(s). I have text like this:

<p>Some text<a href="/relativePath1/file.ext">link</a>.<p>SomeText<img 
src="/relativePath2/file2.ext" style="width: 200.2px; height: 1141px;"></p>

I know that two relative paths, and I want to extract file names, that are situated in this relative path directory. I don't want files from another relative or absolute paths. There can be more occurences of these paths. Extensions may vary.

I have tried this [\w-]+\.\w+, but it collides with style - width property, and it finds also file names from another relative paths in the text. Thanks for you help, in advance.

Additional clarification: I want to find file names that lies in that two relative paths. I know paths, but I dont know which files are there. There can be multiple occurences.

1
  • ok, you have several relative paths, and you just want to match certain file names from certain paths, right ? So which paths are you talking about ? Commented Nov 24, 2013 at 10:09

2 Answers 2

1

Try it:

 '/^[a-zA-Z0-9]+\.[a-zA-Z]{3,4}$/'    

Or maybe use basename()

Sign up to request clarification or add additional context in comments.

1 Comment

Well that's a common mistake, extensions are not limited to only characters and they are certainly not limited to 3 or 4 characters. For example this is a valid name my.tar.gz. Adding ^$ makes no sense in this context.
0

The input is HTML so I would suggest a DOM solution:

$html = <<<EOF
<p>Some text<a href="/relativePath1/file.ext">link</a>.<p>SomeText<img
src="/relativePath2/file2.ext" style="width: 200.2px; height: 1141px;"></p>
EOF;

$doc = new DOMDocument();
$doc->loadHTML($html);

$selector = new DOMXPath($doc);

// select all src and href attributes
foreach($selector->query('//@href | //@src') as $url) {
    // extract the filename from path using basename()
    var_dump(basename($url->nodeValue));
}

Output:

string(8) "file.ext"
string(9) "file2.ext"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.