0

I need your help in my code:

$sentence = "Erzurum da hayat çok monoton SANIRIM:d";
$words = preg_split('/[\s,.\'\-\[\]]+/', $sentence, -1, PREG_SPLIT_NO_EMPTY);

this code splits the sentence into words and the output is below

Array ( [Erzurum] => 1 [da] => 1 [hayat] => 1 [çok] => 1 [monoton] => 1 [SANIRIM:d] => 1)

But I want to split the ":d" character in the last word How can I do this?

gocen
  • 103
  • 1
  • 10

1 Answers1

1

Use a positive look-ahead assertion:

preg_split('/([\s,.\'\-\[\]]+|(?=:))/'

which means "split if the next character is a ':' ". You could also use a look-behind, depending on what you actually intend to use the string for.

user234461
  • 1,133
  • 12
  • 29
  • likely I also need a look-behind assertion. How can I change the code if the emoticon was on the beginning of the word – gocen Jan 02 '14 at 11:41
  • Do you mean you're expecting something like this: ":dHello there"? In that case, you would want to split if there was a colon followed by a certain character, so for example use "'/([\s,.\'\-\[\]]+|(?=:))|(?<=[;:][dop()])/', if the only emoticons you're expecting are ":)" ":(" ";)" ":p" ":o" ":d" and so on. Obviously you'll have to adapt this to your requirements. WARNING: I didn't test this. – user234461 Jan 02 '14 at 22:14
  • Yes I mean that but this code doesn't work. Sample output is like: Array ( [@1elizdoga malesef öyle ] => 1 [:/ üstelik yapacak bişey yok bunun için ] => 1 [:(] => 1 [ @barbar1907 iyi geceler.] => 1 ) – gocen Jan 05 '14 at 12:03
  • Look at the regex: "(?<=[;:][dop()])" means "anything that follows [;:][)(dop]". ";)" is in "[;:][)(dop]". ":/" is not in "[;:][)(dop]", which is why you get ":/ üstelik..." instead of ":/", "üstelik...". In other words, you need to add "/" to the list of possible characters that follow a ':' or a ';'. Be careful with escape characters: you need "\\/" (and if you want ":\" too, you also need "\\\\"). – user234461 Jan 06 '14 at 15:29