Delete symbol from the last position of a string, optimally with PHP

Asked

Viewed 81 times

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 right way to test beanckmark in PHP when we come across these cases?

  • 2

    The two functions presented in the question are not equivalent. It would be good to clarify the "rules" of removal more accurately so that a satisfactory answer is possible. If you put in the post what is the real problem to be solved, it can be even more interesting.

1 answer

0


I believe 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. This reference has some reasons to use and abuse expressions:
http://blog.stevenlevithan.com/archives/10-reasons-to-learn-and-use-regular-expressions

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

I hope I’ve helped.

  • 1

    I have always heard that regular expressions are slower and should be avoided in simple situations. In this case I was in doubt because the solution with string functions has a very large complexity level (check in an array) but, even so could be faster, already the solution with regular expression is simple (only one line) but could have a slower execution. It’s hard to know how much it pays to give up performance for simplicity and vice versa.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.