Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP explode string using a regular expression

Tags:

regex

php

parsing

I have a long string consisting of a series of sentences separated by a single quote.

Example:

This\'s sentence number 1'This\'s sentence number 2'

Notice that the string has single quotes part of the sentence itself which are escaped. I need to explode the string using single quote, but not the escaped single quote.

The output should be:

Array{
      [0]=>This\'s sentence number 1
      [1]=>This\'s sentence number 2
}

Basically I need to explode the string on { ' }, but not { \' }. Thanks in advance.

like image 707
Songo Avatar asked Jan 18 '12 09:01

Songo


People also ask

What is the use of explode () string function in PHP?

explode() is a built in function in PHP used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.

How Preg_match () and Preg_split () function works *?

How Preg_match () and Preg_split () function works *? preg_match – This function is used to match against a pattern in a string. It returns true if a match is found and false if no match is found. preg_split – This function is used to match against a pattern in a string and then splits the results into a numeric array.

What does the explode () function do?

The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string.

What is the purpose of Preg_match () regular expression in PHP?

The preg_match() function will tell you whether a string contains matches of a pattern.


1 Answers

Try this:

print_r(preg_split("/(?<!\\\)\'/", "This\'s sentence number 1'This\'s sentence number 2'"));
like image 107
CSharpRU Avatar answered Sep 21 '22 17:09

CSharpRU