在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(),但对我来说效果并不好。你想做那样的事吗?

<?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

可能不是最有效的方法,但有效。

$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