Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String Replacement

Status
Not open for further replies.

dalhousi

Programmer
Mar 26, 2007
21
CA
Hi Everyone,

How do I replace the "'" in a string with the escape character "\'" in Perl?

or in general: how do I replace a substring with another substring? In PHP: I would use the function str_replace. Is there any function in Perl similar to str_replace?

Thanks in advance
Cheers
 
In general terms:
Code:
$variable =~ s/replace/replace with/g;
"replace" is a regular expression, "replace with" is a string. Remove the 'g' at the end to make it replace just once.

In your case:
Code:
$variable =~ s/'/\\'/g;
Note that the backslash needs to be escaped.
 
I literally just did this for a chatbox script I had written to replace explicit words with another word. I simply used...

$message =~ s/damn/bunnies/;

I place this code directly after i had diclared that $message = param('message');

Before printing the message it will check if the word damn has been used and if it has then it will replace it with bunnies
hehe



 
xmassey

you code will only catch the first damn and stop... you need to put a g on the end of it to catch if they put more than one.

$message =~ s/damn/bunnies/g;
 
yeah your right, I just saw in my book that it also says put g at the end if you want to replace all strings...

Another useful thing is to put i as well, and this ignores the case of the letters

so..

$message =~ s/damn/bunnies/gi;
 
That will also match the character sequence d-a-m-n even if it isn't a word by itself, so it would change "damned" into "bunniesed".
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top