Jump to content

Convert spaces in a string to underscores?


grippat

Recommended Posts

I have a form field on my site that I want to convert whatever the user enters into all lowercase using strtolower(). Then I want to take the string and convert any characters that aren't numbers, letters, or a period to underscores. For example if user entered "My-Awesome File Name.mp3" the PHP script would convert that to "my_awesome_file_name.mp3". How would I go about accomplishing that?

Link to comment
Share on other sites

Take a look at this. You define an array with the characters you want to allow (in this example only lowercase characters were added, so do the strtolower first), and then you can call the str_filter function and send it the string you want to filter, the array of allowed characters, and the replacement character.

<?php$allowed = array();// add lettersfor ($i = 97; $i < 123; $i++)  $allowed[] = chr($i);  // add numbersfor ($i = 0; $i < 10; $i++)  $allowed[] = "{$i}";  // add other$allowed[] = ".";$allowed[] = "_";$string = "some str!ng with bad #chars";echo str_filter($string, $allowed, "_");function str_filter($str, $chars, $repl){  $retval = "";  for ($i = 0; $i < strlen($str); $i++)	$retval .= (in_array($str[$i], $chars) ? $str[$i] : $repl);  return $retval;}?>

Link to comment
Share on other sites

Archived

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

×
×
  • Create New...