The preg_split function stored all results in an array

Having an issue with the preg_split function in PHP.

My regular expression is:

#^(-?[0-9]+)(([+x])(-?[0-9]+))*$#

I am trying to transform this input:

-5+69x45

into an array like this:

{
[0] = -5
[1] = +
[2] = 69
[3] = x
[4] = 45
}

The regular expression works with preg_match, but not with preg_split. It returns an empty array without flags:

{
[0] = -5
[1] = x
[2] = 45
}

Using the flag PREG_SPLIT_DELIM_CAPTURE, I still encounter the same issue. Where could my error be?

Answer №1

It seems there may have been a misunderstanding regarding the usage of preg_split.

Essentially, the pattern you specify is utilized to divide the string, resulting in the parts of the string that match your pattern not being included in the final array.

By implementing the PREG_SPLIT_DELIM_CAPTURE flag, the content within the capturing groups gets appended to the resultant array (preg_spit documentation).

#^(-?[0-9]+)(([+x])(-?[0-9]+))*$#
            ^^^^^^^^^^^^^^^^^^

However, since there is a quantifier around the last two groups, only the final match is stored in $2 and $3. Consequently, the initial match "69+" is overwritten, resulting in:

$1 = -5
$2 = x
$3 = 45

Answer №2

Here is a code snippet for parsing a mathematical expression:

$str = '-5+69x45';
$arr = preg_split('#([+x]|-?\d+)#', $str, 0, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY );
print_r($arr);

OUTPUT:

Array
(
    [0] => -5
    [1] => +
    [2] => 69
    [3] => x
    [4] => 45
)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Eliminate self-closing elements in XPath

I recently came across a helpful solution to eliminate empty tags from my XML file. If you're interested, you can find the solution here. However, I've encountered an issue with this approach when dealing with nested nodes that are empty. Take ...

What could be causing my PHP code to not execute properly alongside the HTML?

I am currently sharpening my skills in PHP by working on a simple web form project. To put it simply, I need to develop a basic web form that accepts a two-dimensional array of European cities along with the distance in kilometers between each pair of citi ...

The jquery error NS_ERROR_XPC_BAD_CONVERT_JS is causing issues on Google Chrome while working fine on Firefox

Currently, I am utilizing jQuery to dynamically add fields to a form. These are considered "repeatable" fields since users can click an "add more" button. Here is the code snippet: $(".add-attacker-scores").click(function() { count = count + 1; ...

PHP download feature enhancement using underscores

My goal is to retrieve and download a file based on the value passed in through POST. However, I'm encountering an issue where if the file name is "Functional requirements example," it gets downloaded as "__Functional." Am I making a mistake here? Th ...

Error message "Authorization issue occurred while trying to call a function in the PHP webservice."

I am facing an issue with calling a web service. It successfully connects and returns its methods, however, when I call one of the functions, it throws an unauthorized error. Here is my code try { $service = new SoapClient("http://www.go-to-orbit.com/oo ...

Events that are loaded using jQuery

My webpage features dynamic content generated by PHP, and I am looking to utilize jQuery's load function to refresh the div container periodically. This will ensure that new content is displayed on top of the existing content. The jQuery function I a ...

Display the most recent product category exclusively in Laravel 5.8

Within my database, I have three entities: products, categories, and product_category. A single product can be associated with multiple categories, and some of these categories may have a parent category. The desired information on how these entities are r ...

Utilize jQuery to extract various input/select box values and compile them into an array for submission using .ajax()

I am currently facing an issue with dynamically generated forms using PHP and updated with jQuery's .appendTo() function as visitors interact with it. My main goal is to collect all input text and select box values from the current form and submit the ...

No default value error occurs when using the set mutator and the update observer is not functioning properly

When I try to save a model, I encounter an error stating that the slug attribute does not have a default value. To resolve this issue, I created a mutator called setSlugAttribute. However, it still gives me the same error. //Inside the Controller's sa ...

Optimal Placement for FB.Event.subscribe

Here is the code I have implemented on my website for the Facebook Like and Share buttons. The functionality works seamlessly. When I click the Like button, a notification is promptly displayed on my Facebook profile page. Additionally, Facebook automatic ...

How to Use jQuery Post Method to Submit a Form Without Redirecting

I am looking to enhance the user experience of my form by preventing it from reloading upon submission. Specifically, I want to trigger the call to index.php when the submit button named "delete-image" is clicked in the scenario outlined below. It's i ...

Obtaining a date and time in PHP from a JavaScript array

I am currently working on implementing a JQuery datetime picker and my goal is to save the selected date and time into a PHP variable for storage in a MySQL database. Despite browsing through various examples, none of them seem to be effective in achieving ...

Steps to include a personalized error message in Laravel when utilizing Rule::in for validation

I am currently working on validating a select dropdown in Laravel using an array of agency names. I have successfully implemented the validation using Rule::in(), which returns a standard error message 'The selected agency-name is invalid'. Howev ...

What steps should I follow to generate an array index within a foreach loop?

I need help transforming an array into a specific format. Currently, I am using a foreach loop to iterate through the array. $role_rights = array(); foreach ($write_read_permission as $k => $val) { $role_rights['menu_url'][] = $k; $ ...

Verify if the elements within an array are distinct. If they are, shuffle the contents of the array

My array contains the following elements: 0 => string '' (length=0) 1 => string 'nameMiddle' (length=10) 2 => string 'dsa' (length=3) 3 => string '' (length=0) 4 => string 'phoneFirst' (leng ...

I am attempting to establish a connection to a database using PDO within the CodeIgniter framework

$database_config = array( 'hostname' => 'mysql:host=myhostname;dbname=test;', 'username' => 'root', 'password' => '', 'database' => 'test', &apo ...

Warning: The username index is not defined in the file C:xampphtdocsindex.php at line 4

Hey there, I just wanted to express my gratitude for taking the time to read this. It's all part of a college assignment (web server scripting unit p4) where I am working on setting up a simple login system. Unfortunately, I keep running into an error ...

The comment section is not appearing on my WordPress blog posts

I've created a unique WordPress site with a custom theme, and I've added comments to my single.php file. Here's what it looks like: <?php get_header();?> <div id="content"> <div class="right"> <div class="article"&g ...

js issue with passing form data to use with PHP mail function

As a novice, I am diving into the world of HTML webpage creation. Utilizing a free online template, my current project involves developing a Contact Page that triggers a php script to send an email with the captured fields. While I've successfully man ...

Error: Unexpected syntax error encountered, the script is looking for a different syntax ("=>")

I encountered this error message "Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ')'" , when attempting to create a 2D array in order to pass two keys into a foreach loop. $productIds = array ( [0] =&g ...