1

In php is there a quick way of replacing every other character (non spaces) in a string with something else ? I searched around and haven't found a solution.

Take something like this:

    $str = "This is my example string!"

And end up with something like this:

    $result = "T*i* i* m* e*a*p*e s*r*n*!
2
  • Just curious; is your plan to use this in a query for searching purposes? Commented Feb 19, 2018 at 15:29
  • 1
    no the plan is to present somewhat minor hidden data back to the user .. it's not sensitive info but we still just want to hide some of the text .. Commented Feb 19, 2018 at 15:41

3 Answers 3

4

Simple preg_replace() solution:

$str = "This is my example string!";
$result = preg_replace('/(\S)\S/', '$1*', $str);

print_r($result);

The output:

T*i* i* m* e*a*p*e s*r*n*!

  • \S - stands for non-whitespace character
Sign up to request clarification or add additional context in comments.

Comments

3

You can treat the string as an array, loop through it and change the character using modulo to check for parity:

<?php
$string = "This is my test string";

$length = strlen($string);
for ($i = 0; $i < $length; $i++) {
    $string[$i] = $i % 2 === 0 ? $string[$i] : "*";
}
echo $string;

Result:

T*i* *s*m* *e*t*s*r*n*

Demo

4 Comments

Thanks, I like this one if I needed to look at each char but I picked the other answer because it was a done with a single command
@MikeQ definitely. I try to avoid regular expressions whenever possible but RomanPerekhrest is much more elegant!
I see, yeah they are "slower" (I suppose) and really can be bungled pretty easily.. Thanks for helping !
Well, you are right, the answer above was more difficult to handle and I went back to yours. I have an issue where the text was breaking the API so I ended up adding a preg_replace before I obfuscate it. So all in all, this is a simple thing but ended up very hard to debug due to the built in commands. Thank you for your feedback sir!
0

preg_replace() is certainly appropriate more direct approach versuses looped processes. The regex doesn't need a capture group and the replacement doesn't need a backreference, use \K to reset the fullstring match. Demo

echo preg_replace('#\S\K\S#', '*', $string);
// T*i* i* m* t*s* s*r*n*

Comments

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.