1

Hi I have the following string consisting of letters and numbers "00G990010020100038" and I want to replace the letter for their ASCII value, in fact there can be only one letter inside the string, the position is what it changes.

I tried using preg_replace with no success, maybe I'm doing something wrong.

preg_replace("/[a-zA-Z]/", ord('$\1'), $mystring)

My code substitutes the letter for ASCII value of character '$' but I want 'G' (in this case) to be replaced.

2 Answers 2

2

Try this:

preg_replace("/[a-zA-Z]/e", "ord('\\0')", $mystring)

The /e modifier lets you execute PHP in the replacement.

2

You could use preg_replace_callback instead. It's more efficient than the e modifier.

preg_replace_callback(
    "/[a-zA-Z]/",
    create_function('$matches','return ord($matches[0]);'),
    $mystring
);

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.