Excluding symbol from the last position of a string, optimally with PHP [closed]

2

I would like to delete the last character of a string if it is a symbol. I know I could do it in a complex way like the following function:

$string = "minha_string_com_simbolo_no_final_";

function excluir($string){
    $simbolos = ["'","\"", "@","#","$","%","&","*", "(",")","-","_","+","=","
    [","]","§","ª","º","{","}","´","'","^","~","?","/",";",":",",",".",",
    ",">","\","|","¬","¢","£"]; 

    if(array_search(substr($string, -1), $simbolos)){
       return substr_replace($string, '', -1);
    }
}

Or extremely simple as the solution below with regular expression:

$string = "minha_string_com_simbolo_no_final_";

print preg_replace("/\W$/", "", $string); 

Which option has a better performance?

What is the correct way to do beanckmark tests in PHP when we come across these cases?

    
asked by anonymous 06.07.2016 / 22:47

1 answer

0

I think the second option is more optimized.

$string = "minha_string_com_simbolo_no_final_";
print preg_replace("/\W$/", "", $string); 

Because it is a regular expression whose purpose is to provide a concise and flexible way of identifying strings of interest. A regular expression is made to identify patterns so you would opt for the second option. In this reference you have some reasons to use and abuse the expressions:
link

If you want to do performance testing, you can take a look at Xdebug .

I hope I have helped.

    
06.07.2016 / 23:12