Skip to content
Advertisement

How to output data from a file using preg match in php

I have used this code to generate the output (file.php)

<?php

function getContents($str, $startDelimiter, $endDelimiter) {
  $contents = array();
  $startDelimiterLength = strlen($startDelimiter);
  $endDelimiterLength = strlen($endDelimiter);
  $startFrom = $contentStart = $contentEnd = 0;
  while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) {
    $contentStart += $startDelimiterLength;
    $contentEnd = strpos($str, $endDelimiter, $contentStart);
    if (false === $contentEnd) {
      break;
    }
    $contents[] = substr($str, $contentStart, $contentEnd - $contentStart);
    $startFrom = $contentEnd + $endDelimiterLength;
  }

  return $contents;
}


$sample = '
<start>One<end>
<start>Two<end>
<start>Four - 565<end>
<start>Five - 556<end>
';
$v = getContents($sample, '<start>', '<end>');

$result = preg_filter('/[0-9]+/', '($0)', $v);

foreach ($result as $value => $name) {
    echo $name;
    echo "<br>";
}




?>

Which actually outputs

Four - (565)
Five - (556)

Example : 127.0.0.1/file.php?username=Four when we go to that url the number to it comes 565.

Is there a way to achieve this with PHP ?

Advertisement

Answer

Well, as you want to stick on this non-XML data and don’t give us more information about the size of the data nor the way to reply if no number is next to the searched item then you could just start off with a simple regular expression like this one.

Regular expression: <start>Four[s-]*(d*)<end>

Play arround with it here: https://regex101.com/r/p0aaGG/1
You’ll have the explanation of the regular expression on regex101.com:

  • In PHP, a regular expression must be surrounded by a starting and ending char and then some flags can be added after. Most often we use the / delimiter like it’s the case in JavaScript. But some persons use # or ~. Example:
    • /Teddy/i will look for the word Teddy but case insensitive.
    • ~Teddy~i is exactly the same regular expression but written with another delimiter. This is why preg_quote() has a second parameter to give the delimiter used if its not the usual slash /.
  • s means any kind of space char.
  • [s-] means any kind of space char or the - char.
  • [s-]* means it can be 0 or multiple times.
  • d means any digit char.
  • d* means any digit char 0 or multiple times.
  • () are used to capture, so that we can get it later in the $matches array.

Now if <start>, <end> and Four are parameters then you could do this in PHP:

<?php

$sample = '<start>One<end>
<start>Two<end>
<start>Four - 565<end>
<start>Five - 556<end>';

function getContents($username, $startDelimiter, $endDelimiter) {
    global $sample;
    
    // The pattern (regex) looks like this: /<start>Four[s-]*(.*?)<end>/
    $pattern = '/' .
        preg_quote($startDelimiter) .
        preg_quote($username) .
        '[s-]*(d*)' .
        preg_quote($endDelimiter) .
        '/';
    
    $matches = [];
    if (preg_match($pattern, $sample, $matches)) {
        return $matches[1];
    }
    else {
        return false;
    }
}

// Test all usernames.
$usernames = [
    'One',
    'Two',
    'Four',
    'Five',
    'unknown user'
];

foreach ($usernames as $username) {
    $result = getContents($username, '<start>', '<end>');
    echo "Result for '$username' is " . var_export($result, true) . "n";
}

The result of this sample script is:

Result for 'One' is ''
Result for 'Two' is ''
Result for 'Four' is '565'
Result for 'Five' is '556'
Result for 'unknown user' is false

For @mebak:

If you just want the result then don’t do the loop over the tested users and read the username from the $_GET or $_POST arrays that PHP fills for us:

// Same as above and then just this:

if (isset($_GET['username'])) {
    $username = $_GET['username'];
}
elseif (isset($_POST['username'])) {
    $username = $_POST['username'];
}
else {
    die("Missing username!");
}

print getContents($username, '<start>', '<end>');
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement