-1

i need to format uppercase words to bold but it doesn't work if the word contains two spaces

is there any way to make regex match only with words which end with colon?

$str = "BAKA NO TEST: hey";    
$str = preg_replace('~[A-Z]{4,}\s[A-Z]\s{2,}(?:\s[A-Z]{4,})?:?~', '<b>$0</b>', $str);

output: <b>BAKA NO TEST:</b> hey

but it returns <b>BAKA</b> NO TEST: hey

the original $str is a multiline text so there are many lowercase and uppercase words but i need to change only some

Eddie D.
  • 145
  • 3
  • 12
  • Your last five questions seem to iteratively refine the same topic. Is the current regex the result of your own attempts or from somewhere else? * See also [Open source RegexBuddy alternatives](http://stackoverflow.com/questions/89718/is-there) and [Online regex testing](http://stackoverflow.com/questions/32282/regex-testing) for some helpful tools, or [RegExp.info](http://regular-expressions.info/) for a nicer tutorial. – mario Jul 30 '13 at 21:32
  • i got this regex from another topic but i've tried to change for what i need but it doesn't work that's why i'm asking for help.. i'm not good with regex...i'm getting new issues based on the first question – Eddie D. Jul 30 '13 at 21:35
  • 2
    What about `$str = preg_replace('/[A-Z\s]+:/', '$0', $str);`? – Phylogenesis Jul 30 '13 at 21:35
  • look at your second `[A-Z]` clause and try to figure out how a single char class could possibly match `NO`. – Marc B Jul 30 '13 at 21:37
  • i got the same output for both regex above – Eddie D. Jul 30 '13 at 21:40

2 Answers2

0

Unless you have some good reason to use that regexp, try something simpler, like:

/([A-Z\s]+):/

Also, just so you know, you can use asterisk to specify none or more space characters: \s*

pajaja
  • 2,164
  • 4
  • 25
  • 33
0

You can do it like this:

$txt = preg_replace('~[A-Z]+(?:\s[A-Z]+)*:~', '<b>$0</b>', $txt);

Explanations:

[A-Z]+      # uppercase letter one or more times
(?:         # open a non capturing group
    \s      # a white character (space, tab, newline,...)
    [A-Z]+  #
)*          # close the group and repeat it zero or more times

If you want a more tolerant pattern you can replace \s by \s+ to allow more than one space between each words.

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
  • it didn't work even with a single space.. for example: `$str = "BAKA TEST" it formats only the first word` – Eddie D. Jul 30 '13 at 21:50
  • @EddieD.: I don't know where you test your patterns, but it works fine. – Casimir et Hippolyte Jul 30 '13 at 21:53
  • i test in my real code.. well.. based on ur example i've changed mine and it worked.. like this `$str = preg_replace('~[A-Z]+(?:\s+[A-Z]+)*:~', '$0', $str['descricao']);` – Eddie D. Jul 30 '13 at 21:55