0

So I'm coding a script to extract particular data fields from strings of semi predictable data, and I'm trying to use PHP to grab the text between say the 70th and 71st counts of a specific character.

So a sample string of data would be as follows...

00000|data|data|data|text|data|data|||

How can I use PHP to grab the "text" between the 4th and 5th "|". The text field changes so I cannot just use a regex to match and extract it. The only logical method I can think of is the use the count of "|" which is predictable each time.

Any idea how I can accomplish this? I'd rate my PHP skills as moderate but no matter what I try I cant get this to work out.

0

2 Answers 2

1

The split option given by @JohnConde in the comments section is one way to go here. You could also use regex replacement:

$input = "00000|data|data|data|text|data|data|||";
$match = preg_replace("/(?:[^|]+\|){4}([^|]+).*$/", "$1", $input);
echo $match;  # text
1
  • or preg_match("/(?:\|?\K[^|]+){5}/", $input, $matches) ? $matches[0] : '' will also work Feb 2, 2021 at 3:30
1

When you have a string that contains characters separated by a common delimiter you can use explode() to split that string into pieces separated by that delimiter and place the pieces into an array. You can then access a piece using standard array access syntax (remembering that arrays start counting at zero).

Step-by-step:

$pieces = explode("|", "00000|data|data|data|text|data|data|||");
echo $pieces[4]; // Get fifth string

Using array dereferencing for shorter syntax:

echo explode("|", "00000|data|data|data|text|data|data|||")[4];
2
  • Correct me if I am wrong, but [4] is "referencing". Dereferencing would be using list() or [$one, $two, $three, $four, $five, $six, $seven, $eight, $nine, $ten] = explode('|', ...); Feb 2, 2021 at 3:21
  • This explosion should be limited to 6 elements, since the OP only needs to access the 5th -- this way you do not waste time exploding 65-odd more times. Feb 2, 2021 at 3:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.