Jump to content

Best method to locate instance of characters within a string.


Jabop

Recommended Posts

Files that users submit may have spaces, hyphens, underscores, and non-url friendly characters (these are images being uploaded to a directory).

 

What I'm trying to do is strip all characters that are not: a-z A-Z 0-9 (excluding hyphens)

I also want to replace spaces with hyphens.

 

I have thought that the best way to achieve this would be using preg_match() to find any existence of X chars within the string, and rename the file accordingly. I'm not the best with regex, but I can manage. If this is the best way, I'll figure it out.

 

What I'm asking, essentially, is does anyone recommend another way of going about this task?

$str = "My Name is Corbin_@$%^^&~~`|\\/";

$str = preg_replace("/[^a-zA-Z0-9 ]/", "", $str); //leave all alpha numeric or space characters.... - will be removed at this point.

$str = str_replace(" ", "-", $str);

 

Edit: forgot the output...

 

$str will now be "My-Name-is-Corbin"

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.