Jump to content

Remove duplicate word


Nyla

Recommended Posts

For some reason, this doesn't work:

 

<?php
$string = 'You have a code   CODE  code of ethics';
while (preg_match("/code\s+code/",$string)) {

$string = preg_replace("/code\s+code/","code",$string);

}

print $string;
?>

 

I don't want to replace all instances of duplicated words, rather, only when the word "code" is duplicated. Throughout my 100mb text file, the word "code" appears duplicated (with varying whitespace between). For example:

 

From this:

You have a code   CODE code   code of ethics.

Code   code Code green means everything is okay.

What is the CODE code     code code for the lock.

 

To this:

You have a code of ethics.

Code green means everything is okay.

What is the code for the lock.

 

But for some reason, I cannot get my preg_replace to work?

Link to comment
Share on other sites

Wtf happened to create all those "code"s?

 

Regular expressions are case-sensitive by default. Use the /i flag to stop that.

While I'm here, you don't need to use a loop for this.

<?php
$string = 'You have a code   CODE  code of ethics';
$string = preg_replace('/code(\s+code)+/i', "code", $string); // "code" and one or more of (whitespace and "code")
print $string;
?>
Link to comment
Share on other sites

Nope, still BIG problem. On your computer, create a text file called "bigfile.txt" with ONE string on it, exactly:

 

Very Good Ethics Code CODE CODE.

 

Now, I run this code (I didn't leave anything out):

 

<?php

#again, "bigfile.txt" is a text file with this exact string: Very Good Ethics Code CODE CODE.
 
$lines = file("bigfile.txt");
foreach ($lines as $n => $line) {
$line = preg_replace('/code(\s+code)+/i', "code", $line);
}
file_put_contents("bigfile.txt", $lines);
?>
 
Nothing got changed (here's the output):
Very Good Ethics Code CODE CODE.
 
If you help me with this, I will buy you a beer (non-alcoholic, because I'm a goody-goody person) if you ever come to my hometown!
Link to comment
Share on other sites

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.