I wrote this code to prepare a title for a link, but I think it is a bit bulky and am wondering if anyone with a better understanding of regex would be able to reduce the following function (by merging the relevant preg_replaces). I need it to strip all current hyphens, strip multiple spaces, ensure that it is solely alphanumeric apart from the space-replacing hyphen, replace all spaces with a single hyphen and ensure that the string doesn't start with a hyphen:
function prepareURLTitle($title)
{
return preg_replace("/\A-/", "", str_replace(" ", "-", preg_replace("/[^a-zA-Z0-9\s]/", "", preg_replace('/\s\s+/', ' ', preg_replace('/\s?-/', '', $title)))));
}
An example of input and it's output:
Input:
BRAND NEW - Gloves, 2 pack //Multiple spaces are in here but the blockquote won't allow me to display them
Output:
BRAND-NEW-Gloves-2-pack
trim(preg_replace('`[^a-z0-9]+`i','-',str_replace("'",'',$title)),'-')
I also replaced quotes with nothing, so strings like "The cat's meow" don't become "The-cat-s-meow".
function prepareURLTitle($title)
{
return preg_replace("[^A-Za-z0-9]+", "-", $title);
}
This should work. You need to replace multiple non-alphanumeric characters with a single "-".
preg_replace('~[^a-z\d]+~i','-',preg_replace('~^[^a-z\d]+(.*?)[^a-z\d]+$~i','$1',$title));
// or
preg_replace(array('~^[^a-z\d]+(.*?)[^a-z\d]+$~i','~[^a-z\d]+~i'),array('$1','-'),$title);
With an example…
$title = ' BRAND NEW - Gloves, 2 pack - ';
echo preg_replace(array('~^[^a-z\d]+(.*?)[^a-z\d]+$~i','~[^a-z\d]+~i'),array('$1','-'),$title);
will return
BRAND-NEW-Gloves-2-pack
function prepareURLTitle($title)
{
return preg_replace( "/[^a-zA-Z0-9]/", "-",str_replace("-", "", $title));
}
DEMO: http://codepad.org/lPSQQBys
OUTPUT:
BRAND-NEW--Gloves--2-pack
Related
I have a form which takes user inputs; Recently, I have come across many user inputs with multiple white spaces.
Eg.
"My tests are working fine!"
Is there any way I can get rid of these white spaces at PHP level or MySQL level?
Clearly trim doesn't work here.
I was thinking of using Recursive function but not sure if there's an easy and fast way of doing this.
my code so far is as below:
function noWhiteSpaces($string) {
if (!empty($string)) {
$string = trim($string);
$new_str = str_replace(' ', ' ', $string);
} else {
return false;
}
return $new_str;
}
echo noWhiteSpaces("My tests are working fine here !");
If the input is actual whitespaces and you want to replace them with a single space, you could use a regular expression.
$stripped = preg_replace('/\s+/', ' ', $input);
\s means 'whitespace' character. + means one or more. So, this replaces every instance of one or more whitespace characters' in $input with a single space. See the preg_replace() docs, and a nice tutorial on regexes.
If you're not looking to replace real whitespace but rather stuff like , you could do the same, but not with \s. Use this instead:
$stripped = preg_replace('/( )+/', ' ', $input);
Note how the brackets enclose .
I have this function that returns me an friendly url string.
public static function getUrlFriendlyString($str) {
// convert spaces to '-', remove characters that are not alphanumeric
// or a '-', combine multiple dashes (i.e., '---') into one dash '-'.
$_str = preg_replace("[-]", "-", preg_replace("[^a-z0-9-]", "",
strtolower(str_replace(" ", "-", $str))));
return substr($_str, 0, 40);
}
Anyway, if I have for example this String:
"Product with vitamins, protein, and a lot of good stuff"
The resulting string is:
"product-with-vitamins,-protein,-and-a-lot-of-good-stuff"
As you can see it doesn't remove the commas from the string :/ and my knowledge about regular expressions is null.
You left out the delimiters around the regexp, so it used [ and ] as the delimiters. As a result, they weren't being treated as the character class operators.
If you want to compress multiple - into one, the regexp is /-+/, not [-].
public static function getUrlFriendlyString($str) {
// convert spaces to '-', remove characters that are not alphanumeric
// or a '-', combine multiple dashes (i.e., '---') into one dash '-'.
$_str = preg_replace("/-+/", "-", preg_replace("/[^a-z0-9-]/", "",
strtolower(str_replace(" ", "-", $str))));
return substr($_str, 0, 40);
}
I currently have this line in my code:
<div>'.ucwords($row[website]).'</div>
And it will display a city name such as this:
Puiol-del-piu
But what I need is for it to display without the dashes and so that ucwords will capitalize the first letter of each word such as this:
Puiol Del Piu
It would be great if the code could be confined to this one line because I have a lot more going on with others stuff in the page as well.
This str_replace does the job:
$string = str_replace("-", " ", $string);
Also, you can make it as a function.
function replace_dashes($string) {
$string = str_replace("-", " ", $string);
return $string;
}
Then you call it:
$varcity = replace_dashes($row[website]);
<div>'.ucwords($varcity).'</div>
<?php
echo '<div>'.ucwords(str_replace("-"," ",$row[website])).'</div>';
In the above example you can use str_replace() to replace hyphens with spaces to create separate words. Then use ucwords() to capitalize the newly created words.
http://php.net/manual/en/function.str-replace.php
http://php.net/manual/en/function.ucwords.php
replace dash with space
str_replace("-"," ",$row[text])
replace space with dash
str_replace(" ","-",$row[text])
str_replace ('Find what you want to replace', 'Replace with ', 'Your array or string variable');
If you want to replace dash with space, you can use this:
str_replace("-"," ",$row[text])
If you want to replace space with dash, use this:
str_replace(" ","-",$row[text])
Use ucwords() to capitalize words.
I was wondering how can I strip white space from elements that are just whitespace and whitespace from all elements from user submitted data using PHP?
lets say if a tag is stripped how can
I stop that from entering the
database?
$sRaw = $_POST[ 'data' ];
$sTrimmed = trim( $sRaw );
if( $sRaw === $sTrimmed ) {
// DB insert code
} else {
// Message was trimmed, show user an error
}
Very simple.
$string = " Whats up I'm cool?";
$string = trim($string);
$string = str_replace(" ", " ", $string);
$string = str_replace(" ", " ", $string);
echo $string; //output is "Whats up I'm cool?"
The reason is for this is because trim() removes any whitespace which is deemed useless thus reducing the total size of the string. The only thing is trim() only removes the whitespace at the beginning and end, so I've added two str_replace() which have been set to remove unwanted whitespace, and because if there's " " (three spaces) one str_replace() won't cut it so I've added it twice, and if you want to, you can add a cycle using foreach() which will trim it until there's no whitespace left but I have wrote it in the basic form as that's what you're asking for.
Depends on the white space... but I believe you are asking about trim() which removes starting and ending whitespace.
echo trim(" v "); //results in "v"
I receive a string from a database query, then I remove all HTML tags, carriage returns and newlines before I put it in a CSV file. Only thing is, I can't find a way to remove the excess white space from between the strings.
What would be the best way to remove the inner whitespace characters?
Not sure exactly what you want but here are two situations:
If you are just dealing with excess whitespace on the beginning or end of the string you can use trim(), ltrim() or rtrim() to remove it.
If you are dealing with extra spaces within a string consider a preg_replace of multiple whitespaces " "* with a single whitespace " ".
Example:
$foo = preg_replace('/\s+/', ' ', $foo);
$str = str_replace(' ','',$str);
Or, replace with underscore, & nbsp; etc etc.
none of other examples worked for me, so I've used this one:
trim(preg_replace('/[\t\n\r\s]+/', ' ', $text_to_clean_up))
this replaces all tabs, new lines, double spaces etc to simple 1 space.
$str = trim(preg_replace('/\s+/',' ', $str));
The above line of code will remove extra spaces, as well as leading and trailing spaces.
If you want to replace only multiple spaces in a string, for Example: "this string have lots of space . "
And you expect the answer to be
"this string have lots of space", you can use the following solution:
$strng = "this string have lots of space . ";
$strng = trim(preg_replace('/\s+/',' ', $strng));
echo $strng;
There are security flaws to using preg_replace(), if you get the payload from user input [or other untrusted sources]. PHP executes the regular expression with eval(). If the incoming string isn't properly sanitized, your application risks being subjected to code injection.
In my own application, instead of bothering sanitizing the input (and as I only deal with short strings), I instead made a slightly more processor intensive function, though which is secure, since it doesn't eval() anything.
function secureRip(string $str): string { /* Rips all whitespace securely. */
$arr = str_split($str, 1);
$retStr = '';
foreach ($arr as $char) {
$retStr .= trim($char);
}
return $retStr;
}
$str = preg_replace('/[\s]+/', ' ', $str);
You can use:
$str = trim(str_replace(" ", " ", $str));
This removes extra whitespaces from both sides of string and converts two spaces to one within the string. Note that this won't convert three or more spaces in a row to one!
Another way I can suggest is using implode and explode that is safer but totally not optimum!
$str = implode(" ", array_filter(explode(" ", $str)));
My suggestion is using a native for loop or using regex to do this kind of job.
To expand on Sandip’s answer, I had a bunch of strings showing up in the logs that were mis-coded in bit.ly. They meant to code just the URL but put a twitter handle and some other stuff after a space. It looked like this
? productID =26%20via%20#LFS
Normally, that would‘t be a problem, but I’m getting a lot of SQL injection attempts, so I redirect anything that isn’t a valid ID to a 404. I used the preg_replace method to make the invalid productID string into a valid productID.
$productID=preg_replace('/[\s]+.*/','',$productID);
I look for a space in the URL and then remove everything after it.
I wrote recently a simple function which removes excess white space from string without regular expression implode(' ', array_filter(explode(' ', $str))).
Laravel 9.7 intruduced the new Str::squish() method to remove extraneous whitespaces including extraneous white space between words: https://laravel.com/docs/9.x/helpers#method-str-squish
$str = "I am a PHP Developer";
$str_length = strlen($str);
$str_arr = str_split($str);
for ($i = 0; $i < $str_length; $i++) {
if (isset($str_arr[$i + 1]) && $str_arr[$i] == ' ' && $str_arr[$i] == $str_arr[$i + 1]) {
unset($str_arr[$i]);
}
else {
continue;
}
}
echo implode("", $str_arr);