Check for capitalized words

Asked

Viewed 1,198 times

-2

How to check if a string contains uppercase words in PHP? I have a log page, check this when the user logs.

  • 3
  • 2

    What do you mean? When finding the uppercase letters does what?

  • 1

    You can use a regex [A-Z]

  • Your question is very wide, explain more what you want, give an example and show where you want to get, recommend the readings quoted by @rubStackOverflow

  • 1

    @Brayan Can you explain the question better? Did the rray answer work? After all, you want to know if the text has 1 or more uppercase letters, whether it is all uppercase, whether it has at least one uppercase word?

2 answers

3


To find out if there are upper case letters in a string you can use a simple regex [A-Z] with the function preg_match().

<?php
$entradas = ['Um', 'min abc', 'aÇão', 'ação', 'CAPS'];

foreach($entradas as $item){
   if(preg_match('/\p{Lu}/u', $item)){
      echo "Entrada: $item - existe pelo menos uma letra maiuscula\n";
   }else{
      echo "Entrada: $item - não existe pelo menos uma letra maiuscula\n";
   }
}   

Example - ideone

  • /[A-Z]*/ evaluates '', 'sominusculas', 'qualquercoisa' to true because Pattern accepts zero *. Even removing the * the solution is not yet robust as it does not deal with Unicode, any É or Ç will be rejected.

  • @brunorb, for Unicode characters just add the u modifier. Then fix it, thanks for the tip

  • @Brunorb changed the answer, it is agreed now?

  • Your code says that all the entries have upper lip, turn to see. It’s almost correct, you need to use the property Lu to specify what are "uppercase Letters", reference. In the case the correct regex is /\p{Lu}/u.

2

Give to do as follows with strtoupper function:

<?php

$palavra = 'PALAVRA1';

if (strtoupper($palavra) == $palavra) {//TRUE
    echo 'Verdadeiro';
}

$palavra = 'pALaVRA1';

if (strtoupper($palavra) != $palavra) {//FALSE
    echo 'Falso';
}

Browser other questions tagged

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