Fueling Your Coding Mojo

Buckle up, fellow PHP enthusiast! We're loading up the rocket fuel for your coding adventures...

Popular Searches:

Strip php variable, replace white spaces with dashes

Hey everyone,

I am currently working on a PHP project and I need some help with a particular task. I want to strip a PHP variable and replace any white spaces with dashes. Can someone please guide me on how to achieve this?

To provide a little context, I have a variable called $productName, which holds the name of a product. Sometimes, this name contains spaces and that's causing some issues when I'm trying to use it in certain functions or URLs. To overcome this, I believe I need to strip the variable of any spaces and replace them with dashes.

I'm not sure about the exact functions or methods to use in PHP to accomplish this. So if any experienced developers could share their insights and suggest the most efficient way to achieve this, it would be greatly appreciated.

Looking forward to your help and guidance. Thanks in advance!

All Replies


Hey fellow developers,

I had a similar situation in one of my recent PHP projects and found a different approach to stripping a PHP variable and replacing white spaces with dashes. Instead of using str_replace() and trim(), you can utilize the preg_replace() function with a regular expression.

Here's an example of how I achieved it:

$productName = "This is my awesome product";
$productSlug = preg_replace("/\s+/", "-", $productName);

In this case, the regular expression `/\s+/` matches any group of whitespace characters (including spaces, tabs, and line breaks), and the preg_replace() function replaces these matches with dashes.

After running this code, you'll get the modified product name stored in the $productSlug variable as "This-is-my-awesome-product".

This regex-based method worked well for me, especially when dealing with various types of whitespace. Give it a try and let me know if you have any further questions or concerns!

Best regards,


Hey there!

I've encountered a similar issue before while working on a PHP project. To strip a PHP variable and replace white spaces with dashes, you can use the str_replace() function along with trim(). Here's how I usually implement it:

$productName = "My Product Name";
$productSlug = trim(str_replace(" ", "-", $productName));

In this example, I'm replacing all occurrences of spaces with dashes using str_replace(). The trim() function is used to remove any leading or trailing spaces that might be present in the variable.

After executing this code, the $productSlug variable will contain the modified product name with spaces replaced by dashes, giving you something like "My-Product-Name".

I hope this helps you out! Let me know if you have any further questions.

New to LearnPHP.org Community?

Join the community