I'm trying to replace all of the consecutive spaces with just one underscore; I can easily replace one space with "_" by using the following line of code:
str_replace(" ", "_",$name);
Evan I can replace one spaces with "_" by following line of code:
str_replace(" ", "_",$name);
But the problem is I don't know how many blank spaces I have to check!
If my question is not clear please let me know which part you need more clarification.
Thanks
Probably the cleanest and most readable solution:
preg_replace('/[[:space:]]+/', '_', $name);
This will replace all spaces (no matter how many) with a single underscore.
You can accomplish this with a regular expression:
[ ]+
This will match "one or more space characters"; if you want "any whitespace" (including tabs), you can instead use \s+.
Using this with PHP's preg_replace():
$name = preg_replace('/[ ]+/', '_', $name);
Use preg_replace():
$name = preg_replace('/ +/', '_', $name);
+ in regex means "repeated 1 or more times" hence this will match [SPACE] as well as [SPACE][SPACE][SPACE].
You can use regular expressions:
$name = preg_replace("#\s+#", "_", $name);
Related
This should be obvious, but I'm having trouble.
I want to replace several characters (dashes, spaces, underscores) with an empty string, but I've got something wrong.
This code: $tmp = preg_replace('/[ -_]/', '', 'filename-1055');
...returns this: "filename"
...when I'm expecting this: "filename1055"
Why the truncation?
Try str_replace instead:
$tmp = str_replace(array("-", "_", " "), "", 'filename-1055');
Unless there is a particular reason you are using preg_replace.
In a character class, dash - is the range operator, so your class [ -_] means any character in the range (space) to _.
You have two possibilities:
1- move the dash in the first or last position in the character class: [- _] or [ _-]
2- or escape it: [ \-_]
Try this way, DEMO
$re = "/([-\\s_])/";
$str = "filename-1055\n";
$subst = "";
$result = preg_replace($re, $subst, $str, 1);
Its because you did not escape - (range operator inside []) with \-. Correct code would be:
$tmp = preg_replace('/[ \-_]/', '', 'filename-1055');
I'm trying to remove all words of less than 3 characters from a string, specifically with RegEx.
The following doesn't work because it is looking for double spaces. I suppose I could convert all spaces to double spaces beforehand and then convert them back after, but that doesn't seem very efficient. Any ideas?
$text='an of and then some an ee halved or or whenever';
$text=preg_replace('# [a-z]{1,2} #',' ',' '.$text.' ');
echo trim($text);
Removing the Short Words
You can use this:
$replaced = preg_replace('~\b[a-z]{1,2}\b\~', '', $yourstring);
In the demo, see the substitutions at the bottom.
Explanation
\b is a word boundary that matches a position where one side is a letter, and the other side is not a letter (for instance a space character, or the beginning of the string)
[a-z]{1,2} matches one or two letters
\b another word boundary
Replace with the empty string.
Option 2: Also Remove Trailing Spaces
If you also want to remove the spaces after the words, we can add \s* at the end of the regex:
$replaced = preg_replace('~\b[a-z]{1,2}\b\s*~', '', $yourstring);
Reference
Word Boundaries
You can use the word boundary tag: \b:
Replace: \b[a-z]{1,2}\b with ''
Use this
preg_replace('/(\b.{1,2}\s)/','',$your_string);
As some solutions worked here, they had a problem with my language's "multichar characters", such as "ch". A simple explode and implode worked for me.
$maxWordLength = 3;
$string = "my super string";
$exploded = explode(" ", $string);
foreach($exploded as $key => $word) {
if(mb_strlen($word) < $maxWordLength) unset($exploded[$key]);
}
$string = implode(" ", $exploded);
echo $string;
// outputs "super string"
To me, it seems that this hack works fine with most PHP versions:
$string2 = preg_replace("/~\b[a-zA-Z0-9]{1,2}\b\~/i", "", trim($string1));
Where [a-zA-Z0-9] are the accepted Char/Number range.
I have this string here photo of the day - 2011 and I need to look like photo-of-the-day-2011 when I do a str_replace, I get this output:
photo-of-the-day---2011 what can I do to fix this?
Here is the code:
$albumName = 'photo of the day - 2011'; (this comes from a db and cannot change it)
$albumName = str_replace(" ", "-", $albumName);
You can use the more powerful preg_replace, instructing it to replace runs of dashes and/or spaces with a single dash:
$name = preg_replace('/[\s-]+/', '-', $name);
[\s-]+ is a regular expression that matches "one or more of: whitespace and dashes".
I know this question has been asked several times for sure, but I have my problems with regular expressions... So here is the (simple) thing I want to do in PHP:
I want to make a function which replaces unwanted characters of strings. Accepted characters should be:
a-z A-Z 0-9 _ - + ( ) { } # äöü ÄÖÜ space
I want all other characters to change to a "_". Here is some sample code, but I don't know what to fill in for the ?????:
<?php
// sample strings
$string1 = 'abd92 s_öse';
$string2 = 'ab! sd$ls_o';
// Replace unwanted chars in string by _
$string1 = preg_replace(?????, '_', $string1);
$string2 = preg_replace(?????, '_', $string2);
?>
Output should be:
$string1: abd92 s_öse (the same)
$string2: ab_ sd_ls_o
I was able to make it work for a-z, 0-9 but it would be nice to allow those additional characters, especially äöü. Thanks for your input!
To allow only the exact characters you described:
$str = preg_replace("/[^a-zA-Z0-9_+(){}#äöüÄÖÜ -]/", "_", $str);
To allow all whitespace, not just the (space) character:
$str = preg_replace("/[^a-zA-Z0-9_+(){}#äöüÄÖÜ\s-]/", "_", $str);
To allow letters from different alphabets -- not just the specific ones you mentioned, but also things like Russian and Greek, or other types of accent marks:
$str = preg_replace("/[^\w+(){}#\s-]/", "_", $str);
If I were you, I'd go with the last one. Not only is it shorter and easier to read, but it's less restrictive, and there's no particular advantage to blocking stuff like и if äöüÄÖÜ are all fine.
Replace [^a-zA-Z0-9_\-+(){}#äöüÄÖÜ ] with _.
$string1 = preg_replace('/[^a-zA-Z0-9_\-+(){}#äöüÄÖÜ ]/', '_', $string1);
This replaces any characters except the ones after ^ in the [character set]
Edit: escaped the - dash.
in my functions.php if have this code:
echo ''.urldecode($search).'';
this removes the special chars..
but how can i additonally add remove space and replace it with - and remove "
so, if someone types in "yo! here" i want yo-here
Try:
<?php
$str = '"yo! here"';
$str = preg_replace( array('/[^\s\w]/','/\s/'),array('','-'),$str);
var_dump($str); // prints yo-here
?>
If you want to replace a run of unwanted characters with a single dash, then you can use something like this:
preg_replace('/\W+/', '-', $search);
To remove surrounding quotes, and then replace any other junk with dashes, try this:
$no_quotes = preg_replace('/^"|"$/', '', $search);
$no_junk = preg_replace('/\W+/', '-', $no_quotes);
This will replace multiple spaces / "special" chars with a single hyphen. If you don't want that, remove the "+".
You might want to trim off any trailing hyphens, should something end with an exclamation point / other.
<?php
preg_replace("/\W+/", "-", "yo! here check this out");
?>
You can remove any non-words:
preg_replace('/\W/', '-', $search);