Regex for single quotes

Asked

Viewed 804 times

5

I would like to remove the single quotes in the middle of a text, ignoring the ones at the beginning and end, if any.

  • 1st Case: 'Texto e pala'vras' = 'Texto e palavras'

  • 2nd Case: Texto e pala'vras = Texto e palavras

  • You really need a regex? str_replace() does not solve the problem?

  • cannot replace all, I have to preserve the simple quotation marks of the beginning and the end.

2 answers

10


You can use the regex (?<!^)'(?!$).

The syntax (?<! determines a negative lookbehind, that is, it checks if something does not exist before the current position. Within this lookbehind we have the bookmark ^, which means "string start".

Then we have our own character '.

Right after we have (?!, which determines a Lookahead negative. Similarly to lookbehind, it checks if something does not exist after the current position. Inside it we have the bookmark $, meaning "end of string".

That is, regex takes all characters ' (single quotes), as long as they are not at the beginning or end of the string. Thus, we can use this regex in the function preg_replace (remembering to escape the character ' with \):

$texto = '\'Texto e pala\'vras\'';
$texto = preg_replace('/(?<!^)\'(?!$)/', '', $texto);
echo $texto;

The preg_replace replaces all these quotes with an empty string (i.e., in practice these quotes are removed from the string). The result is 'Texto e palavras'.

  • 2

    That’s all I needed. I didn’t know you could use Lookahead that way. Thank you so much.

3

You can solve this problem alternatively with str_replace() and substr(). First all single quotes are removed, then a check is made with substr() if the first and last characters are single quotes and at the end printf/sprintf() assemble the final template.

function removerAspas($str){
    $str = trim($str);
    $aspaInicio  = substr($str, 0, 1) == "'" ? "'" : '';
    $aspaFim = substr($str, -1, 1)  == "'" ? "'" : '';
    $strLimpa = str_replace("'", '', $str);

    return sprintf("%s%s%s", $aspaInicio, $strLimpa, $aspaFim);
}

echo removerAspas("'Texto e pala'vras'") .PHP_EOL;
echo removerAspas("Texto e pala'vras#'") .PHP_EOL;
echo removerAspas("'#Texto e pala'vras") .PHP_EOL;
echo removerAspas("Te'x'to' 'e' pala'vras") .PHP_EOL;

Example - ideone

Browser other questions tagged

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