Jump to content

[SOLVED] replacing symbols help


xnowandtheworldx

Recommended Posts

I'm making a script, and I need to replace every symbol, like, `, ~, , , !, @, ETC. ETC. but instead of just replacing everyone if there are two in a row i still need it to only replace the symbols with only 1 "_"...and also remove any "_" that would be at the end after being replaced...heres an example...

 

The.losers! => the_losers

The..losers!! => the_losers

php!!rules:D => php_rules_D

 

so any help would be nice..i didn't really know how to explain lol.

Link to comment
https://forums.phpfreaks.com/topic/100722-solved-replacing-symbols-help/
Share on other sites

Eh,

 

Warning: preg_replace() [function.preg-replace]: No ending delimiter '`' found in /home/a5206629/public_html/bruce/test_r.php on line 5

 

$pattern="`~!@";
$replace = "the..losers..!~";
preg_replace($pattern,$replace,$string);

echo $string;

 

the line with the error is the preg_replace(); line

Here's my shot at it.

 

<?php

$regex = '/[\W_]++/'; // Match one or more characters that is a non-word character or underscore as many times as possible
$subject = 'Hello, my name\'s Matt! I _hate_ non-word..characters';

$result = preg_replace($regex, '_', $subject);

echo $result;

// Outputs:
//	Hello_my_name_s_Matt_I_hate_non_word_characters

?>

 

If you want to maintain underscores (ie __ not converted to _) just change the regex to this

 

$regex = '/[\W]++/';

  • 4 weeks later...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.