Automatic line break with regex

Asked

Viewed 162 times

2

I have the following string: $var = "Saudi Arabia U23 x South Korea U23"; I want to divide the names that are separated by "x", I did the following:

$arr = preg_split('/[v|x]/', $var);

I used "V e X" because sometimes the string can come with a "v" separating the names, and not X, the problem is that if you have an "x" or "v" included in the name, other than the "x" or "v" of the separation, it will cut too, but I just want to separate the names delimited by " x " or " v ". How would you do it in regex?

  • 1

    This is logically impossible. Do you have a way to change the tab using characters that do not appear in the name? , for example with -(Hyphen)

2 answers

3


Just put spaces followed by + out of square brackets:

$arr = preg_split('/ +[v|x] +/', $var);

This regex will remove the characters " x ", " v " and also those who have more than one space such as "   x " and " v    "

  • 1

    Perfect! That’s what I couldn’t do. Thanks!

  • 1

    Its regex allows the pipe to be a delimiter, it within a list loses its function of OU/OR logical.

1

This regex solves the problem, it searches for one or more spaces followed by one v or x followed by one or more spaces.

$str = 'abc X edfxct';
$arr = preg_split('/\s+v|x\s+/i', $str);

echo "<pre>";
print_r($arr);

Exit:

Array
(
    [0] => abc 
    [1] => edfxct
)
  • Very good! thanks for the help

Browser other questions tagged

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