John Davidson

php - Preg_split matching preset number of instances from right to left

0 comments
Message:


I'm hoping that there's some way in regex to match certain characters by counting from right to left.


I have a text like the one below where the fields are inconsistent, except that they are delimited by spaces, except the name, which has an indeterminate number of spaces. There are no enclosing marks.


NAME WITH SPACES FIELD1 FIELD2 FIELD3 FIELD4
SECOND NAME WITH SPACES FIELD1 FIELD2 FIELD3 FIELD4
THIRD NAME WITH SPACES FIELD1 FIELD2 FIELD3 FIELD4
FOURTH NAME WITH SPACES FIELD1 FIELD2 FIELD3 FIELD4
FIFTH NAME WITH SOME MORE SPACES FIELD1 FIELD2 FIELD3 FIELD4

I needed to break this up using the last 4 spaces to get the column values and using what's left as the name. I'm about to do this by splitting on all spaces and using the last 4 values in the array, but isn't there a way to do this with regex that I can split the line by the last four spaces? I imagine that it would be looking from right to left in this case.


This particular project is in php using PCRE.



My Answer:
You can achieve this using a combination of regex and PHP's `preg_split` function. Here's an example code snippet that demonstrates how you can split the text by the last four spaces:

php
$text = "NAME WITH SPACES FIELD1 FIELD2 FIELD3 FIELD4_SECOND NAME WITH SPACES FIELD1 FIELD2 FIELD3 FIELD4_THIRD NAME WITH SPACES FIELD1 FIELD2 FIELD3 FIELD4_FOURTH NAME WITH SPACES FIELD1 FIELD2 FIELD3 FIELD4_FIFTH NAME WITH SOME MORE SPACES FIELD1 FIELD2 FIELD3 FIELD4";

// Match the last four spaces and split the text
$parts = preg_split('/\s+(?=\S*(?:\s+\S+){0,3}$)/', $text);

// Output the results
print_r($parts);


In this code snippet, the regex pattern `\s+(?=\S*(?:\s+\S+){0,3}$)` is used to match the last four spaces in the text. The `preg_split` function then splits the text based on this pattern, resulting in an array of parts where the last four spaces are used as delimiters.

You can adjust the regex pattern as needed to match different numbers of spaces or to include additional conditions for splitting the text.

Rate this post

3 of 5 based on 7766 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us