Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Replace and Lowercase

Tags:

replace

php

I am trying to do a PHP replace like ASP Replace. The function just returns a blank value though?

    $zonename=mysql_real_escape_string($_POST["zonename"]);
    $zname_clean =""; # blank string
    $zname_clean = $zonename; # fill string with the post form
    $zname_clean = str_replace($zname_clean, " ", ""); # remove white space

That is my code. Example Zonename would be "Header Left", I want to remove capitalization and also remove whitespace.

How can I remove whitespace and convert the case and also is there a cleaner way of doing this?

like image 844
TheBlackBenzKid Avatar asked Jan 05 '12 11:01

TheBlackBenzKid


People also ask

How do I lowercase a word in PHP?

The strtolower() function converts a string to lowercase. Note: This function is binary-safe. Related functions: strtoupper() - converts a string to uppercase.

How can I replace special characters in a string in PHP?

The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array. If the string to be searched is an array, find and replace is performed with every array element.

How do I use Strtolower?

strtolower() - It converts a string into uppercase. lcfirst() - It converts the first character of a string into lowercase. ucfirst() - It converts the first character of a string into uppercase. ucwords() - It converts the first character of each word in a string into uppercase.

How do I convert a string to lowercase?

Java String toLowerCase() Method The toLowerCase() method converts a string to lower case letters. Note: The toUpperCase() method converts a string to upper case letters.


2 Answers

// strip out all whitespace
$zname_clean = preg_replace('/\s*/', '', $zname_clean);
// convert the string to all lowercase
$zname_clean = strtolower($zname_clean);

See the PHP manual for strtolower() and preg_replace().

like image 195
Treffynnon Avatar answered Oct 20 '22 01:10

Treffynnon


You have your parameters in the wrong order. Take a look at this: http://php.net/manual/en/function.str-replace.php

It should be str_replace(" ", "", $zname_clean);

Another way of doing this is strtolower(trim($zname_clean));

like image 35
OptimusCrime Avatar answered Oct 20 '22 00:10

OptimusCrime