replace with php all alphanummeric chars with X or x (case sensitive)

假如想象 提交于 2020-07-22 10:42:59

问题


I have the following variables:

$var1 = "23 Jan 2014";
$var2 = "Some Text Here - More Text is written here";

How can I replace the text so the output looks like this:

$var1 = "XX Xxx XXXX";
$var2 = "Xxxx Xxxx Xxxx - Xxxx Xxxx xx xxxxxx xxxx";

Edit: The variables can change. I simply want to replace all A-Za-z0-9 from any variable with X (for capital letters), x (for small letters) and X (for numbers).


回答1:


Use double regular expressions - one for the upper case + numbers and one for the lower case. Something like this.

$var = preg_replace('/[A-Z0-9]/', 'X', $var);
$var = preg_replace('/[a-z]/', 'x', $var);



回答2:


Enhanced response to Hinz :)
In one shot :

$res = preg_replace(array('#[A-Z0-9]#', '#[a-z]#'), array('X', 'x'), $src);



回答3:


Here is a non reg-exp method. Personally I'd rather use the reg-exp method though.

<?php
$var1 = "23 Jan 2014";
echo convertStringToXX($var1);

$var2 = "Some Text Here - More Text is written here";
echo convertStringToXX($var2);

function convertStringToXX($input)
{
    $output = '';
    for($key = 0; $key < strlen($input); $key++)
    {
        $char = $input[$key];
        $ord = ord($char);

        if($ord >= 97 && $ord <= 122)
        {
            $output .= 'x';
        }
        elseif(($ord >= 65 && $ord <= 90) || ($ord >= 48 && $ord <= 57))
        {
            $output .= 'X';
        }
        else
        {
            $output .= $char;
        }
    }
    return $output;
}


来源:https://stackoverflow.com/questions/28381345/replace-with-php-all-alphanummeric-chars-with-x-or-x-case-sensitive

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!