0

I'm trying to use preg_replace() to remove all hexadecimal characters in a string (with only lower case letters):

$line = "sjdivfriyaaqa\xd2vkmpcuyyuen";
$line = preg_replace('/\\x[0-9a-f]{2}/', '', $line);
echo($line);

This should, as I understand it, echo sjdivfriyaaqavkmpcuyyuen ($line with \xd2 removed) but it echoes the original $line. Why?

2 Answers 2

1

This will work

$line = "sjdivfriyaaqa\\xd2vkmpcuyyuen";
$new = preg_replace('/\\\x[0-9a-f]{2}/', '', $line);
echo($new);

You need another blackslash to escape it in the string, if you try echoing it right away you will see that it's empty.

Sign up to request clarification or add additional context in comments.

Comments

1

In fact the double quotes "" interpretes escaped char \ meaning "\xd2" is 'Ò' for instance.

Using simple quote '' your code is ok:

$line = 'sjdivfriyaaqa\xd2vkmpcuyyuen';
$line = preg_replace('#\\\x[0-9a-f]{2}#', '', $line);
echo($line);

1 Comment

btw why three backslashes ? \\\ => two \\ results to the real \ char, the third means the char is escaped, four \ will be ok too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.