0

I have to determine the position of a special character in the string for example:

E77eF/74/VA on 6 and 9 position (counting from 1) we have '/' so I have to change them to position number -> E77eF6749VA

On MSSQL I could use PATINDEX but I need to use php for this. It should work for everything except 0-9a-zA-Z

I found strpos() and strrpos() on php.net but I doens't work well for me. Anyway tries to do something like that?

4

2 回答 2

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

于 2015-07-04T17:55:57.007 回答
0

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

$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
于 2015-07-04T17:43:06.430 回答