Replace All Characters That Aren’t Letters And Numbers With A Hyphen

You can use regular expressions and the preg_replace function in PHP to replace all characters that aren’t letters or numbers with a hyphen. Here’s an example:

$string = "Hello, World! 1234";
$newString = preg_replace("/[^a-zA-Z0-9]+/", "-", $string);

echo $newString;



In this example, the regular expression /[^a-zA-Z0-9]+/ matches any character that is not a letter (upper or lower case) or a number. The ^ inside the square brackets negates the character class. The + after the character class ensures that consecutive non-alphanumeric characters are treated as one match. Finally, the preg_replace function replaces all matches with a hyphen ("-").

Note that this will remove any special characters, spaces, and other non-alphanumeric characters from the string.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!