Regex replace special characters with hyphen except first and last - php

I'm using this regular expression to format song names to url friendly aliases. It replaces 1 or more consecutive instances of special characters and white space with a hyphen.
$alias = preg_replace("/([^a-zA-Z0-9]+)/", "-", trim(strtolower($name)));
This works fine so if the song name was This is *is* a (song) NAME it would create the alias this-is-a-song-name. But if the name has special characters at the beginning or end *This is a song (name) it would create -this-is-a-song-name- creating hyphens at each end.
How can I modify the regex to replace as it is above, but to replace the first and last special character with empty space.

You need to do a double replacement.
$str = '*This is a song (name)';
$s = preg_replace('~^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$~', '', $str);
echo preg_replace('~[^a-zA-Z0-9]+~', '-', $s);

You can perform that in 2 steps:
In the first step, you remove special characters at the beginning and at the end of your string
In the second step, you reuse your regex as it is now.
The code could look like this:
$alias = preg_replace("/(^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$)/", "", trim(strtolower($name));
$alias = preg_replace("/([^a-zA-Z0-9]+)/", "-", $alias);
(I haven't tested it but you may get the idea)

Related

PHP - Removing Brackets and Special Characters

I'm looking to modify a PHP string so I can use it as an anchor tag.
I used the method found here: Remove all special characters from a string
It worked well to remove ampersands from my strings, but it doesn't seem to be removing or affecting the brackets or punctuation.
Here's what I'm currently using:
$name_clean = preg_replace('/ [^A-Za-z0-9\-]/', '', $name); // REMOVES SPECIAL CHARACTERS
$name_slug = str_replace(' ', '-', $name_clean); // REPLACES SPACES WITH DASHES IN TITLE
$link = strtolower( $name_slug ); // CREATES LOWERCASE SLUG VERSION OF TITLE_SLUG
My string (in this case $name) = St. John's (Newfoundland).
The output I get = #st.-john'snewfoundland)
I'd like to remove the periods, apostrophes and brackets altogether.
Any help would be greatly appreciated!
Your regex pattern / [^A-Za-z0-9\-]/ appears to contain a space after the opening /. This pattern will only match a special character that comes after a space. Removing that space should get the result you want.

Replace all characters except first one and whitespaces

Hi
I trying do something like that:
I've got some string - 'Hello World!' for example.
And I want replace all character in it except the first one and white spaces.
so... result will be: "H.... ......";
I don't want delete it, just replacing with "." or other character.
I tried doing this with preg_replace but with no results.
You can do it like so:
$hidden = preg_replace('/(?!^)\S/', '.', $text);
It works by ensuring that we aren't at the beginning of the string with a negative lookahead for the start of string anchor, then matches a non-whitespace character using the negated whitespace character class.
preg_replace('/(?<!^)\S/', '.', $s)

Returning only 0-9 and dashes from string

I would like to take a string, and strip any characters apart from 0-9 and - (dashes).
Example:
if I have a string that looks like:
10-abc20-30
How can I make this string return
10-20-30
(Strip all characters besides numbers and dashes)
Is there some kind of regex to use within preg_match or str_replace ?
$result = preg_replace('/[^\d-]+/', '', $subject);
[^\d-] matches any character except digits or dash; the + says "one or more" of those, so adjacent characters will be replaced at once.
Assuming your data is in $string, this will remove all characters except for dashes and digits
$string = preg_replace('/[^-0-9]/', null, $string);

How to replace one or more consecutive spaces with one single character?

I want to generate the string like SEO friendly URL. I want that multiple blank space to be eliminated, the single space to be replaced by a hyphen (-), then strtolower and no special chars should be allowed.
For that I am currently the code like this:
$string = htmlspecialchars("This Is The String");
$string = strtolower(str_replace(htmlspecialchars((' ', '-', $string)));
The above code will generate multiple hyphens. I want to eliminate that multiple space and replace it with only one space. In short, I am trying to achieve the SEO friendly URL like string. How do I do it?
You can use preg_replace to replace any sequence of whitespace chars with a dash...
$string = preg_replace('/\s+/', '-', $string);
The outer slashes are delimiters for the pattern - they just mark where the pattern starts and ends
\s matches any whitespace character
+ causes the previous element to match 1 or more times. By default, this is 'greedy' so it will eat up as many consecutive matches as it can.
See the manual page on PCRE syntax for more details
echo preg_replace('~(\s+)~', '-', $yourString);
What you want is "slugify" a string. Try a search on SO or google on "php slugify" or "php slug".

Replace all spaces and special symbols with dash in URL using PHP language

How to replace spaces and dashes when they appear together with only dash in PHP?
e.g below is my URL
http://kjd.case.150/1 BHK+Balcony- 700+ sqft. spacious apartmetn Bandra Wes
In this I want to replace all special characters with dash in PHP. In the URL there is already one dash after "balcony". If I replace the dash with a special character, then it becomes two dashes because there's already one dash in the URL and I want only 1 dash.
I'd say you may be want it other way. Not "spaces" but every non-alphanumeric character.
Because there can be other characters, disallowed in the URl (+ sign, for example, which is used as a space replacement)
So, to make a valid url from a free-form text
$url = preg_replace("![^a-z0-9]+!i", "-", $url);
If there could be max one space surrounding the hyphen you can use the answer by John. If there could be more than one space you can try using preg_replace:
$str = preg_replace('/\s*-\s*/','-',$str);
This would replace even a - not surrounded with any spaces with - !!
To make it a bit more efficient you could do:
$str = preg_replace('/\s+-\s*|\s*-\s+/','-',$str);
Now this would ensure a - has at least one space surrounding it while its being replaced.
This should do it for you
strtolower(str_replace(array(' ', ' '), '-', preg_replace('/[^a-zA-Z0-9 s]/', '', trim($string))));
Apply this regular expression /[^a-zA-Z0-9]/, '-' which will replace all non alphanumeric characters with -. Store it in a variable and again apply this regular expression /\-$/, '' which will escape the last character.
Its old tread but to help some one, Use this Function:
function urlSafeString($str)
{
$str = eregi_replace("[^a-z0-9\040]","",str_replace("-"," ",$str));
$str = eregi_replace("[\040]+","-",trim($str));
return $str;
}
it will return you a url safe string

Categories