John Davidson

Correct regex format for taking two values from textfile separated by pipe-delimiter - PHP

0 comments
Message:


I want to retrieve values from a local textfile named "text.txt". After retrieval, PHP would then create a multidimensional array containing said values. The values inside the textfile are separated by a pipe-delimiter and I aim to


This is the content of the textfile - "text.txt".


ExampleOne|23
Ryan|24
Sample Name|25.6
Dogg|31.5

This is the PHP code I've written:


<?php

$file = fopen("text.txt", "r");
$data = array();

while (!feof($file)) {
$line = trim(fgets($file));
if (preg_match('/--I don't know the format--/', $line, $matches)) {
$data[] = array(
'Name' => $matches[0]),
'BMI' => $matches[1],
);
}
}

fclose($file);
?>

And this is the output I'm trying to achieve.


Array
(
[0] => Array
(
[Name] => ExampleOne
[BMI] => 23
)

[1] => Array
(
[Name] => Ryan
[BMI] => 24
)

[2] => Array
(
[Name] => Sample Name
[BMI] => 25.6
)

[3] => Array
(
[Name] => Dogg
[BMI] => 31.5
)
)

My issue comes with incorrect regex format. I can't seem to create the proper format to do what I aim for.


I'm open for suggestions. I'm not sure if preg_match() is the ideal way to achieve what I'm trying to achieve, but from what I've seen so far, it might be so. Its just a matter of figuring the proper regex format.



My Answer:
data.txt that are separated by a pipe-delimiter. The correct regex format for this task in PHP would be:

php
$pattern = '/^(.*?)\|(.*?)$/';


This regex pattern will match lines in the textfile that have two values separated by a pipe-delimiter. The values will be captured in two separate capturing groups, which can be accessed using the `preg_match()` function in PHP.

Rate this post

4 of 5 based on 6117 votes

Comments




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