PHP replace all spaces with hyphens
Use a regular expression changing multiple spaces or hyphens with one hyphen:
$final = preg_replace('#[ -]+#', '-', $text);
Replacing spaces only between words with a hyphen and remove all other spaces
You could trim the $string
first
$string = " Cow jumped over the moon ";
$string_with_dashes = str_replace(' ','-',trim($string));
echo $string_with_dashes;
If you want to reduce multiple spaces between the words you can match 1+ horizontal whitespaces \h+
the replace those with a hyphen.
$string_with_dashes = preg_replace("/\h+/", "-", trim($string));
Strip php variable, replace white spaces with dashes
This function will create an SEO friendly string
function seoUrl($string) {
//Lower case everything
$string = strtolower($string);
//Make alphanumeric (removes all other characters)
$string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
//Clean up multiple dashes or whitespaces
$string = preg_replace("/[\s-]+/", " ", $string);
//Convert whitespaces and underscore to dash
$string = preg_replace("/[\s_]/", "-", $string);
return $string;
}
should be fine :)
Replace Dash with Space in PHP
<?php
echo '<div><a href="http://www.envisionforce.com/local/'.$row[website].'-seo-services">'.ucwords(str_replace("-"," ",$row[website])).'</a></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
Php make spaces in a word with a dash
Oldschool without regex
$test = "jjfnj 948";
$test = str_replace(" ", "", $test); // strip all spaces from string
echo substr($test, 0, 3)."-".substr($test, 3); // isolate first three chars, add hyphen, and concat all characters after the first three
How to replace spaces with dash and remove some characters?
preg_replace
will do the job for you:
preg_replace(array('/[\\/:\*\?"<>|\.,;]+/', '/\s/'), array('', '-'), 'Strange string.');
Check out some manuals for help.
Replace space with hyphen in link
You can do it like this if you want:
<a href="/quote/tag/<?php echo str_replace(" ", "-", get_post_meta($post->ID, 'user_submit_customauthor2', true)); ?>">My Link></a>
Related Topics
Converting Dates with PHP for Datetime in SQL
Move Value in PHP Array to the Beginning of the Array
Replace the Last Comma in a String Using Regular Expression
PHP Type Hinting Not Getting Along with Interfaces and Abstract Classes
Nginx + PHP-Fpm 7.1 - 504 Gateway Time-Out
How to Inject a Service in Another Service in Symfony
Php's Simplexml: How to Use Colons in Names
How to Call Entity Manager in a Constructor
Yii2 Links Between Frontend and Backend (Advanced Template)
How to Send a File via Axios to Laravel
How to Run PHP Code from File_Get_Contents or File in a Function