Search code examples
phpstringalgorithmreplacepatindex

Determine the position of a special character in the string in PHP


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?


Solution

  • <?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);
    
    ?>
    

    Output:

    E77eF6749VA