【问题标题】:Determine the position of a special character in the string in PHP在PHP中确定字符串中特殊字符的位置
【发布时间】:2015-07-04 17:34:41
【问题描述】:

我必须确定一个特殊字符在字符串中的位置,例如:

E77eF/74/VA 在 6 和 9 位置(从 1 开始计数) 我们有 '/' 所以我必须将它们更改为位置编号 -> E77eF6749VA

在 MSSQL 上,我可以使用 PATINDEX,但我需要为此使用 php。 它应该适用于除 0-9a-zA-Z 之外的所有内容

我在 php.net 上找到了 strpos()strrpos(),但我的工作并不顺利。 无论如何尝试做这样的事情?

【问题讨论】:

    标签: php string algorithm replace patindex


    【解决方案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

    【讨论】:

      【解决方案2】:

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

      $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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-11
        • 2012-09-05
        • 1970-01-01
        • 2011-08-29
        • 1970-01-01
        相关资源
        最近更新 更多