iosiki
iosiki

Reputation: 41

String difference in PHP

I have an input string $foo which contains both alphanumeric and non-alphanumeric characters.

I use ereg_replace to $foo to replace all non-wanted chars with empty chars. Now I want to know what were these "erased" chars. How can I do this?

Upvotes: 1

Views: 200

Answers (3)

Matthew
Matthew

Reputation: 48284

In PHP 5.3:

$text = 'Hello, World!';
$stripped = '';
$text = preg_replace_callback('/([^A-Za-z0-9]+)/',
   function($m) use (&$stripped) { $stripped .= $m[0]; return ''; }, $text);

echo "$text\n$stripped\n";

Output:

HelloWorld
, !

Upvotes: 1

Daniel Lubarov
Daniel Lubarov

Reputation: 7924

You could use

$foo = "something";
$bar = ereg_replace(...);
array_diff(chunk_split($foo, 1), chunk_split($bar, 1));

Upvotes: 1

Trey
Trey

Reputation: 5520

If you're using regex to replace, why don't you just use the same regex and do a "preg_match", then a "preg_replace"

Upvotes: 1

Related Questions