John Magnolia John Magnolia - 1 year ago 88
PHP Question

regular expression which validates a relative URL

How would I validate a string to check that it is safe for a URL. No spaces or special characters in the filename which may break the URL in gmail.


data/Logo - free.png
would be invalid

I would only like:
"a-z", "0-9", ".", "-", "_"

There are hundreds of questions for validating URLs on here but they all seem to check if it contains "http" which I dont need.

UPDATE with working code (from @minitech):

// validate filename
if (preg_match('/[^\w.-]/', basename($logo))){
$error = true

Answer Source

Just taking it right from what you listed:

$valid = !preg_match('/[^\w.-]/', $name);

You might consider just escaping it using urlencode, depending on the situation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download