Jump to content

str_replace looking for a better method. or ideas on how to improve


monkeytooth

Recommended Posts

What I have here is what I am thinking is something to strip out all bad characters from a given string. What I am trying to do is strip out everything leaving only the letters and words and safe char's for output to use in a URL.

 

$array_2strip = array("'", '"', ":", ";", "&", "\n", "\t", "\r", "%20", "<", ">", "?", "@", "#", "$", "^", "*", "(", ")", "=", "+", "~", "`", "|", "..", "...", " ");
$booktitlelink = str_replace($array_2strip, '-', $booktitle);
echo $booktitlelink ."<br />";
$array_2strip2 = array("--", "---");
$booktitlelink2 = str_replace($array_2strip2, '-', $booktitlelink);
echo $booktitlelink2 ."<br />";

 

Outputs:

Starting out With Java: From Control.. - With CD

Starting-out-With-Java--From-Control----With-CD

Starting-out-With-Java-From-Control--With-CD

 

 

any ideas on how I can improve on the above? I am trying to mimic wordpress's SEO URL's main issue is the DB I am working with is a wreck and entirely tooo large to go through and edit manually, so I have to filter the outputs like this

Yea, I was reading up on SEO linking, and even a majority of sites recommend try keeping it to just - if at all possible.

 

So, what would I do with preg_match? can preg_match do in string replacements? cause I am generally creating these on the fly, from stored records in a database.

So if that doesn't work, its just all about the regex, I didn't think that worked with preg_ match/replace. But seeing as it does, if that doesnt work 100% im sure if i play with regex a bit i can come up with something to work properly enough. Thank you

the pattern string is pretty simple

( ) - grab this as a variable

[ ] - charaters in range

^ - negate (characters not in this range)

a-zA-Z0-9- - alpha-numerics as well as -

 

so it should grab everything else, and change it to '-'

 

Thank you, that is one of my pitfalls with regex, I am not to clear on how it works, that last post actually helps me better understand it if at the least just enough to dabble and better grasp it, as I use regex alot, but usually preformated strings I have to dig for. Hey side question, do you know of either any good books or online tutorials on regex, that kind of dumb it down for people new to it?

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.