在PHP中判断字符串中特殊字符的位置
Determine the position of a special character in the string in PHP
我必须确定字符串中特殊字符的位置,例如:
E77eF/74/VA 在第 6 位和第 9 位(从 1 开始计数)
我们有 '/' 所以我必须将它们更改为位置编号 -> E77eF6749VA
在 MSSQL 上我可以使用 PATINDEX 但我需要为此使用 php。
它应该适用于除 0-9a-zA-Z
之外的所有内容
我在 php.net 上找到了 strpos()
和 strrpos()
,但我不太适合。
无论如何尝试做那样的事情?
可能不是最有效的方法,但有效。
$string = 'E77eF/74/VA';
$array = str_split($string);
foreach($array as $key => $letter){
if($letter == '/'){
$new_string.= $key+1;
}
else{
$new_string.= $letter;
}
}
echo $new_string; // prints E77eF6749VA
<?php
$content = 'E77eF/74/VA';
//With this pattern you found everything except 0-9a-zA-Z
$pattern = "/[_a-z0-9-]/i";
$new_content = '';
for($i = 0; $i < strlen($content); $i++) {
//if you found the 'special character' then replace with the position
if(!preg_match($pattern, $content[$i])) {
$new_content .= $i + 1;
} else {
//if there is no 'special character' then use the character
$new_content .= $content[$i];
}
}
print_r($new_content);
?>
输出:
E77eF6749VA
我必须确定字符串中特殊字符的位置,例如:
E77eF/74/VA 在第 6 位和第 9 位(从 1 开始计数) 我们有 '/' 所以我必须将它们更改为位置编号 -> E77eF6749VA
在 MSSQL 上我可以使用 PATINDEX 但我需要为此使用 php。 它应该适用于除 0-9a-zA-Z
之外的所有内容我在 php.net 上找到了 strpos()
和 strrpos()
,但我不太适合。
无论如何尝试做那样的事情?
可能不是最有效的方法,但有效。
$string = 'E77eF/74/VA';
$array = str_split($string);
foreach($array as $key => $letter){
if($letter == '/'){
$new_string.= $key+1;
}
else{
$new_string.= $letter;
}
}
echo $new_string; // prints E77eF6749VA
<?php
$content = 'E77eF/74/VA';
//With this pattern you found everything except 0-9a-zA-Z
$pattern = "/[_a-z0-9-]/i";
$new_content = '';
for($i = 0; $i < strlen($content); $i++) {
//if you found the 'special character' then replace with the position
if(!preg_match($pattern, $content[$i])) {
$new_content .= $i + 1;
} else {
//if there is no 'special character' then use the character
$new_content .= $content[$i];
}
}
print_r($new_content);
?>
输出:
E77eF6749VA