0

I want to create a regex in php that matches all characters excluding ; but including all newlines. I can match all characters except ; easily with the regex:

[^;]

And I can match any character including newlines with the regex:

.*/s

But I'm not sure how to combine the two to get the result I desire. I would prefer not having to create a large regex that includes all numbers, symbols, etc.

1 Answer 1

1

Just use:

[^;]+

This will match newlines (since they are not ;), you just have to tell it to match more than just one character.

Demo: Regex101


Implementation:

$string = 'foo
bar
abc;123
test
';

preg_match_all('/[^;]+/', $string, $matches);
var_dump($matches);

// array(1) {
//   [0]=>
//   array(2) {
//     [0]=>
//     string(13) "foo
// bar
// abc"
//     [1]=>
//     string(11) "123
// test
// "
//   }
// }

Alternative:

Is there a chance you just want to use str_replace() or explode(), here are examples using the same $string as above:

$string = str_replace(';', '', $string);
var_dump($string);

// string(24) "foo
// bar
// abc123
// test
// "

OR

$parts = explode(';', $string);
var_dump($parts);

// array(2) {
//   [0]=>
//   string(13) "foo
// bar
// abc"
//   [1]=>
//   string(11) "123
// test
// "
// }
Sign up to request clarification or add additional context in comments.

1 Comment

If this doesn't do what you want, please elaborate on your question of an expected input/match.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.