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".
Related
my string may be like this:
# *lorem.jpg,,, ip sum.jpg,dolor ..jpg,-/ ?
in fact - it is a dirty csv string - having names of jpg images
I need to remove any non-alphanum chars - from both sides of the string
then - inside the resulting string - remove the same - except commas and dots
then - remove duplicates commas and dots - if any - replace them with single ones
so the final result should be:
lorem.jpg,ipsum.jpg,dolor.jpg
I firstly tried to remove any white space - anywhere
$str = str_replace(" ", "", $str);
then I used various forms of trim functions - but it is tedious and a lot of code
the additional problem is - duplicates commas and dots may have one or more instances - for example - .. or ,,,,
is there a way to solve this using regex, pls ?
List of modeled steps following your words:
Step 1
"remove any non-alphanum chars from both sides of the string"
translated: remove trailing and tailing consecutive [^a-zA-Z0-9] characters
regex: replace ^[^a-zA-Z0-9]*(.*?)[^a-zA-Z0-9]*$ with $1
Step 2
"inside the resulting string - remove the same - except commas and dots"
translated: remove any [^a-zA-Z0-9.,]
regex: replace [^a-zA-Z0-9.,] with empty string
Step 3
"remove duplicates commas and dots - if any - replace them with single ones"
translated: replace consecutive [,.] as a single
instance
regex: replace (\.{2,}) with .
regex: replace (,{2,}) with ,
PHP Demo:
https://onlinephp.io/c/512e1
<?php
$subject = " # *lorem.jpg,,, ip sum.jpg,dolor ..jpg,-/ ?";
$firstStep = preg_replace('/^[^a-zA-Z0-9]*(.*?)[^a-zA-Z0-9]*$/', '$1', $subject);
$secondStep = preg_replace('/[^a-z,A-Z0-9.,]/', '', $firstStep);
$thirdStepA = preg_replace('(\.{2,})', '.', $secondStep);
$thirdStepB = preg_replace('(,{2,})', ',', $thirdStepA);
echo $thirdStepB; //lorem.jpg,ipsum.jpg,dolor.jpg
Look at
https://www.php.net/manual/en/function.preg-replace.php
It replace anything inside a string based on pattern. \s represent all space char, but care of NBSP (non breakable space, \h match it )
Exemple 4
$str = preg_replace('/\s\s+/', '', $str);
It will be something like that
Can you try this :
$string = ' # *lorem.jpg,,,, ip sum.jpg,dolor .jpg,-/ ?';
// this will left only alphanumirics
$result = preg_replace("/[^A-Za-z0-9,.]/", '', $string);
// this will remove duplicated dot and ,
$result = preg_replace('/,+/', ',', $result);
$result = preg_replace('/\.+/', '.', $result);
// this will remove ,;. and space from the end
$result = preg_replace("/[ ,;.]*$/", '', $result);
I want to write a PHP function that keeps only a-z (keeps all letters as lowercase) 0-9 and "-", and replace spaces with "-".
Here is what I have so far:
...
$s = strtolower($s);
$s = str_replace(' ', '-', $s);
$s = preg_replace("/[^a-z0-9]\-/", "", $s);
But I noticed that it keeps "?" (question marks) and I'm hoping that it doesn't keep other characters that I haven't noticed.
How could I correct it to obtain the expected result?
(I'm not super comfortable with regular expressions, especially when switching languages/tools.)
$s = strtolower($s);
$s = str_replace(' ', '-', $s);
$s = preg_replace("/[^a-z0-9\-]+/", "", $s);
You did not have the \- in the [] brackets.
It also seems you can use - instead of \-, both worked for me.
You need to add multiplier of the searched characters.
In this case, I used +.
The plus sign indicates one or more occurrences of the preceding element.
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);
I want to convert all the non-alphanumerical characters to hyphens (-) (dashes) for an elegant URL. For this purpose I am using the following method:
$title = 'Any Authentic PHP Script / Third Party & # 10 $ tool to';
$title .= 'Convert HTML to BBcode, BBcode to HTML';
$url = preg_replace("/[^0-9a-zA-Z ]/m", "", $title );
$url = preg_replace("/ /", "-", $url);
It outputs the following:
Any-Authentic-PHP-Script--Third-Party---10--tool-to-Convert-HTML-to-BBcode-BBcode-to-HTML
But, as you will have noticed, there are some unwanted double hyphens (--) and some triple hyphens (--) in the output. I want only one hyphen between each word. How can I achieve my target?
For your code, just replace
$url = preg_replace("/ /", "-", $url);
to
$url = preg_replace("/\s+/", "-", $url);
And get all your spaces (and tabs and so on) convert to only one hyphen. \s means any space character, and + means one or more of the previous token
However, you can do better. Replace both your regexes into one preg_replace
$url = preg_replace("/\W+/m", "-", $title );
...because \W precisely mean non-alphanumeric characters.
In addition, if you also don't want underscores (_) in your result, use
$url = preg_replace("/[\W_]+/m", "-", $title );
As a side note, next time if you genuinely want to do
preg_replace("/ /", "-", $url);
please do this instead
str_replace(" ", "-", $url);
Because str_replace is much faster than preg_replace and is even recommended from PHP docs:
http://php.net/manual/en/function.str-replace.php
If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of preg_replace().
It's because first all non-alphanumerical characters are removed, so your string becomes
Any Authentic PHP Script Third Party 10 tool to
You're seeing it already—leaving double spaces at some places.
Just do this:
preg_replace("/[^a-zA-Z0-9]+/", "-", $subject);
It replaces all occurences of one or multiple non-alphanumerical characters to a single dash.
I have a date variable with the format
2008 12 29
to have it correctly display from within my database app I need the format to be
2008-12-29
Is there a way to simply add the - into the string or replace the spaces with -?
I am using PHP and the date is stored in $release_date
Use str_replace():
$release_date = str_replace(' ', '-', $release_date);
The str_replace() method is what you search for:
$good_format_date = str_replace(' ', '-', $date);
If you know for a fact that the spaces will always be standard (spacebar) spaces, use str_replace() as BoltClock said.
However, if it's possible that there may be extra spaces, tabs, or other whitespace characters in between your date parts, use preg_replace() as it will work in almost all cases unlike str_replace():
$release_date = preg_replace( '/\s+/', '-', $release_date );