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
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

Link to comment
Share on other sites

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]++/';

Link to comment
Share on other sites

A small coment.

I agree that the pattern /[\W]+/ is the best to use.

But we need one more regex. You stated you didn't wan't _ at the end of words.

You will need to do a replace with a pattern like this: /_(\s)|_$/

That will remove _ when space or end of line after it.

Link to comment
Share on other sites

  • 4 weeks later...
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.