Current Location: Home> Latest Articles> How to Use PHP Regular Expressions to Convert a String to an Array

How to Use PHP Regular Expressions to Convert a String to an Array

gitbox 2025-06-14

1. Define the Regular Expression

When converting a string to an array, regular expressions play a crucial role. First, we need to define a regular expression suitable for the target string in order to match specific characters and achieve the conversion from string to array.

Based on the format of the target string, we can use the following regular expression:

$regex = '/\s*,\s*/';

This regular expression matches strings separated by commas and removes any white spaces following each comma.

2. Convert the String to an Array

The steps to convert a string to an array are as follows:

Step 1: Remove Quotes from the Start and End of the String

First, we need to remove any quotes at the start and end of the input string. This can be done using PHP's `trim()` function, as shown in the following example:

$str = trim($str, "'");

Step 2: Split the String into an Array

Next, we use the regular expression to split the string into an array. Here's the code to do that:

$arr = preg_split($regex, $str);

This code will split the string according to the regular expression we defined earlier and store the result in an array.

3. Full PHP Code Example

Here’s a complete PHP code example that demonstrates how to convert a string to an array using a regular expression:

$str = "'apple', 'orange', 'banana'";<br>$regex = '/\s*,\s*/';<br>$str = trim($str, "'");<br>$arr = preg_split($regex, $str);<br>print_r($arr);

Running the above code will output the following result:

Array ( [0] => apple [1] => orange [2] => banana )

With this code, you can convert any comma-separated string into a PHP array.