-4

For example, here is my string :

$text = "Iphone 4, Iphone 4S; Iphone 5, Iphone 3. Iphone 3S";

And splitting string:

$splitting_strings = array(".", ";", ".");
$result = array (
   0 => "Iphone 4",
   1 => "Iphone 4S",
   2 => "Iphone 5",
   3 => "Iphone 3",
   4 => "Iphone 3S"
);

I am using this code:

$regex = '/(' . implode('|', $splitting_strings) . ')/';
print_r(implode($regex, $text));
Makesh
  • 1,236
  • 1
  • 11
  • 25
Hai Truong
  • 200
  • 1
  • 1
  • 8
  • 2
    What is the problem? What are you trying to achieve? You cannot use different characters as delimiter when joining string, if that is what you want to do. – Felix Kling Jul 20 '12 at 09:20
  • When you say `when meet character special` do you mean special characters for RegEx? Please give examples. – Alvin Wong Jul 20 '12 at 09:20
  • It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. – Madara's Ghost Jul 20 '12 at 09:21
  • I think @Hai Trunong wants the output mentioned by $text on imploding the array mentioned by $result using glues comma,semicolon and dot.Still Not sure what is required – Makesh Jul 20 '12 at 09:39

3 Answers3

2

You can using preg_split

$text = "Iphone 4, Iphone 4S; Iphone 5, Iphone 3. Iphone 3S"; 
$array = preg_split("/[\s]*[,][\s]*/", $text);
print_r($array);
// Array ( [0] => Iphone 4 [1] => Iphone 4S [2] => Iphone 5 [3] => Iphone 3 [4] => Iphone 3S )

EDIT:

$array = preg_split("/[\s]*[,]|[;]|[.][\s]*/", $text);
  • your code will split the string based on comma only . The result will be like : Array ( [0] => Iphone 4 [1] => Iphone 4S; Iphone 5 [2] => Iphone 3 . Iphone 3S ) – Makesh Jul 20 '12 at 09:34
  • @HaiTruong : If splitting is your aim ,then what this mean "How to implode a string " ??? .Please give proper title.Dont confuse every one. – Makesh Jul 20 '12 at 09:57
1
<?php
$text = "Iphone 4, Iphone 4S; Iphone 5, Iphone 3. Iphone 3S";

$splitting_strings = array_map( 'preg_quote', array('.', ';', '.', ',' ) );

$result = array_map( 'trim', preg_split( '~' . implode( '|', $splitting_strings ) . '~', $text ) ); 

The value of $result is now the same as yours. Mind that I've used both preg_quote (to escape the characters) as trim.

Berry Langerak
  • 18,561
  • 4
  • 45
  • 58
0

Just to show an alternative to using regexp (though a regexp solution is more efficient).

$text = "Iphone 4, Iphone 4S; Iphone 5, Iphone 3. Iphone 3S";
$separators = ',;.';

$word = strtok($text, $separators);
$arr = array();
do {
    $arr[] = $word;
    $word = strtok($separators);
} while (FALSE !== $word);

var_dump($arr);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385