打招呼, 我试图反转字母而不影响特殊字符。我尝试了一些东西,但没有用。我希望有人能帮助我找出错误。预先感谢。
<?php
function Remove($val){
$r = strlen($val)-1;
$j = 0;
$pattern ='/[\'\/~`\!@#\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';
while($j < $r){
if(preg_match($pattern,$val[$j])){
$j++;
}
else if(preg_match($pattern,$val[$r])){
$r--;
}else{
$j++;
$r--;
list($val[$j],$val[$r]) = array($val[$j],$val[$r]);
}
}
}
$val = "<brinh!>";
echo(Remove($val));
?>
答案 0 :(得分:0)
没有正则表达式的一种解决方案是:
function revert(string $input) : string {
// get all characters; asuming ascii
$chars = [];
for($i = 0; $i < strlen($input); $i++) {
if (ctype_alpha($input[$i])) {
$chars[] = $input[$i];
}
}
// replace characters
for($i = 0;$i < strlen($input); $i++) {
if (ctype_alpha($input[$i])) {
$input[$i] = array_pop($chars);
}
}
return $input;
}
$val = "<brinh!>";
echo revert($val);
具有两个指针,一个指针从左到右运行,一个指针从右到左运行也是可能的。但是可读性差得多。
答案 1 :(得分:0)
<?php
function reverse_string($string) {
$len = strlen($string);
$string_to_array = [];
$special_characters = [];
for($i = 0; $i < $len; $i++) {
// keep special characters and their current position in a new array
if(preg_match('#[^a-zA-Z0-9]#', $string[$i])) {
$pos = stripos($string, $string[$i]);
$special_characters[$pos] = $string[$i];
} else {
// push only normal characters
array_push($string_to_array, $string[$i]);
}
// reverse the normal characters
$reversed_string = array_reverse($string_to_array);
}
// loop through special characters and add them to the reversed array at their original position
foreach($special_characters as $key => $value) {
array_splice($reversed_string, $key, 0, $value);
}
// convert array to string
$array_to_string = implode('', $reversed_string);
return $array_to_string;
}
echo reverse_string('ab!t*cde$');