PHP, Match line, and return value - php

I have multiple lines like this in a file:
Platform
value: router
Native VLAN
value: 00 01
How can I use PHP to find 'Platform' and return the value 'router'
Currently I am trying the following:
$file = /path/to/file
$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$value.*\$/m";
if(preg_match_all($pattern, $contents, $matches)){
echo "Found Data:\n";
echo implode("\n", $matches[0]);
}
else{
echo "No Data to look over";
}

Heres another simple solution
<?php
$file = 'data.txt';
$contents = file($file, FILE_IGNORE_NEW_LINES);
$find = 'Platform';
if (false !== $key = array_search($find, $contents)) {
echo 'FOUND: '.$find."<br>VALUE: ".$contents[$key+1];
} else {
echo "No match found";
}
?>
returns

Here is a really simple solution with explode.
Hope it helps.
function getValue($needle, $string){
$array = explode("\n", $string);
$i = 0;
$nextIsReturn = false;
foreach ($array as $value) {
if($i%2 == 0){
if($value == $needle){
$nextIsReturn = true;
}
}else{
// It's a value
$line = explode(':', $value);
if($nextIsReturn){
return $line[1];
}
}
$i++;
}
return null;
}
$test = 'Platform
value: router
Native VLAN
value: 00 01 ';
echo getValue('Platform', $test);
If the trailing spaces are a problem for you, you can use trim function.

Related

Grab data from text document

I'm trying to grab data from a row in a text file.
I am searching for a value and the subsequent data after the pipe.
userlist.txt:
micky.mcgurk#test.co|Test
michelle.mcgurk#test.co|Test2
PHP:
<?php
$user = "micky.mcgurk";
$file = "userlist.txt";
$search_for = $user;
$contents = file_get_contents($file);
$pattern = sprintf('/\b%s#([^|\s]+)\|/m', preg_quote($search_for));
if (preg_match_all($pattern, $contents, $matches)) {
echo implode("\n", $matches[1]);
$resultat = substr(strrchr($contents, '|'), 1);
echo $resultat;
} else {
echo "No user found";
}
$resultat should equal Test however I get Test2.
It would be easier if you are splitting the string instead of using a RegExp.
<?php
$user = "micky.mcgurk";
$file = "userlist.txt";
$search_for = $user; // Why so many? Redundant right? Why not remove this?
$contents = file_get_contents($file);
$lines = explode(PHP_EOL, $contents);
$resultat = "";
$found = false;
foreach ($lines as $line) {
$line = explode("|", $line);
if ($user . "#test.co" == $line[0]) {
$resultat = $line[1];
echo $line[1];
}
}
if ($resultat == "") {
echo "User not found";
}
There is only a little detail missing in your Regular Expression.
You are looking for this Regular Expression:
$pattern = sprintf('/%s#[^|]+\|(.*)$/m', preg_quote($search_for));
The Content your are looking for will be filled in at $matches[1][0].
I just changed your Script a bit to visualize the different steps of the Search:
<?php
$user = "micky.mcgurk";
$file = "userlist.txt";
$search_for = $user;
$contents = file_get_contents($file);
$pattern = sprintf('/%s#[^|]+\|(.*)$/m', preg_quote($search_for));
echo "ptn: '$pattern'\n";
if (preg_match_all($pattern, $contents, $matches)) {
echo "mtch: '" . print_r( $matches, true) . "'\n";
$resultat = $matches[1][0];
echo "res: '$resultat'\n";
} else {
echo "No user found";
}
?>
So it produces this Output:
$ php userlist.php
ptn: '/micky\.mcgurk#[^|]+\|(.*)$/m'
mtch: 'Array
(
[0] => Array
(
[0] => micky.mcgurk#test.co|Test
)
[1] => Array
(
[0] => Test
)
)
'
res: 'Test'
Also working ...
function startsWith($haystack, $needle)
{
$length = strlen($needle);
return (substr($haystack, 0, $length) === $needle);
}
$contents = "micky.mcgurk#test.co|Test\n\r\michelle.mcgurk#test.co|Test2";
$user = "micky.mcgurk";
$contentLines = explode(PHP_EOL, $contents);
$userExists = False;
$result;
foreach ($contentLines as &$line) {
if (startsWith($line, $user))
{
$userExists = True;
echo explode("|",$line)[1];
}
}

echo $string does not print array elements while string returned by a function

How to get this
function render($string, $array)
{
$pattern = '/[^{{=]*[\w][}}$]/';
preg_match_all($pattern, $string, $matches);
foreach($matches as $tt)
{
$index = '';
foreach($tt as $match1){
$match = str_replace('}', '', $match1);
if (strpos($match,'.') !== false)
{
$string_parts = explode('.', $match);
//print_r($string_parts);
foreach($string_parts as $part)
{
$index .="['".$part."']";
}
}
else
{
$index ="['".$match."']";
}
//echo '$array'.$index;
$new_str = str_replace("{{=".$match."}}", '{$array'.$index.'}' , $string);
$index = '';
//echo $new_str;
$string = $new_str;
}
}
return $string;
}
$arr = [
'site'=>'smartprix',
'users'=>[
['name'=>'user1', 'contact'=>'1234'],
['name'=>'user2', 'contect'=>'4321']
],
'location'=>['address'=>['pincode'=>'123456', 'city'=>'Noida'],
'near'=>'mamura']
];
$array = $arr;
//echo "{$array['site']}"; //It is printing smartprix
$string = "{{=site}} is located at pincode {{=location.address.pincode}}";
echo render($string, $array);
// it is printing "{$array['site']} is located at pincode {$array['location']['address']['pincode']}" why it not convert $array['site'] into the value. I read on php manual and got some reference that {} do not work on returned string then what is the method so that i can print array values after returning the string ?
You can print your expected string is.
echo $string = $array['site']." is located at pincode ".$arr['location']['address']['pincode'];

How to dynamically replace text between symbols and replace with a constant in PHP?

I have a problem where I need to search a HTML page/snippet and replace any value that is between four percentile symbols and convert to a constant variable, e.g. %%THIS_CONSTANT%% becomes THIS_CONSTANT.
Right now I am searching through the page, line by line, and I am able to find matches and replace them by using preg_match_all and preg_replace.
$file_scan = fopen($directory.$file, "r");
if ($file_scan) {
while (($line = fgets($file_scan)) !== false) {
if(preg_match_all('/\%%(.*?)\%%/', $line, $matches)){
foreach($matches as $match){
foreach($match as $m){
$repair = preg_replace('/\%%(.*?)\%%/', $m, $m);
if(preg_match('/\%%(.*?)\%%/', $m, $m)){
} else {
echo $repair.' '.$j;
$j++;
}
}
$lines[$i] = preg_replace('/\%%(.*?)\%%/', constant($repair), $line);
}
} else {
$lines[$i] = $line;
}
$i++;
}
$template[$name] = implode("", $lines);
fclose($file_scan);
}
What this code is not able to do is find and replace multiple matches on a single line. For instance, if there is a line with:
<img src="%%LOGO_IMAGE%%"><h1>%%TITLE%%</h1>
The above code would replace both items with the same value (TITLE). It would also give the error couldn't find constant on the first loop, but work correctly on the second.
This happens very rarely, but I just wish to know how to modify multiple instances on a single line just to be safe.
Edit:
I am able to replace the majority of the code with this:
$file_scan = fopen($directory.$file, "r");
if ($file_scan) {
while (($line = fgets($file_scan)) !== false) {
$line = preg_replace('/\%%(.*?)\%%/', '$2'.'$1', $line);
echo $line;
}
fclose($file_scan);
My last issue is changing the replaced items to constants. Is that possible?
Final Edit:
With the help from Peter Bowers suggestion, I used preg_replace_callback to add the ability to change the keyword to a constant:
foreach($filenames as $file){
$name = str_replace('.html', '', $file);
$template[$name] = preg_replace_callback('/\%%(.*?)\%%/', function($matches){
$matches[0] = preg_replace('/\%%(.*?)\%%/', '$1', $matches[0]);
return constant($matches[0]);
}, file_get_contents($directory.$file));
}
return $template;
Here's a much simpler implementation.
$file_scan = fopen($directory.$file, "r");
if ($file_scan) {
$out = '';
while (($line = fgets($file_scan)) !== false) {
$out .= preg_replace('/\%%(.*?)\%%/', '$1', $line);
$i++;
}
$template[$name] = $out;
fclose($file_scan);
}
Or, even simpler:
$str = file_get_contents($directory.$file);
$template[$name] = preg_replace('/\%%(.*?)\%%/', '$1', $str);
And, since we're going totally simple here...
$template[$name] = preg_replace('/\%%(.*?)\%%/', '$1', file_get_contents($directory.$file));
(Obviously you are losing some of your error checking capabilities as we approach the one-liner, but - hey - I was having fun... :-)
Try with this:
<?php
define('TITLE', 'Title');
define('LOGO_IMAGE', 'Image');
$lines = array();
$file_scan = fopen($directory.$file, "r");
if ($file_scan) {
while (($line = fgets($file_scan)) !== false) {
if(preg_match_all('/\%%(.*?)\%%/', $line, $matches)){
for($i = 0; $i < count($matches[0]); $i++) {
$line = str_replace($matches[0][$i], constant($matches[1][$i]), $line);
}
$lines[] = $line;
print_r($line);
}
}
}
$template[$name] = implode("", $lines);
fclose($file_scan);
?>

Multiple preg_match to check result in Multiple Lines

I want to check preg_match with multiple $line... here is my code
$line = "Hollywood Sex Fantasy , Porn";
if (preg_match("/(Sex|Fantasy|Porn)/i", $line)){
echo 1;}else {echo 2;}
now i want to check in many likes some thing like
$line = "Hollywood Sex Fantasy , Porn";
if (preg_match("/(Sex|Fantasy|Porn)/i", $line, $line1, $line2)){
echo 1;}else {echo 2;}
something like above code with $line1 $line2 $line3
If just one line has to match, you can simply concatenate the lines into a single string:
if (preg_match("/(Sex|Fantasy|Porn)/i", "$line $line1 $line2")) {
echo 1;
} else {
echo 2;
}
This works like an OR condition; match line1 or line2 or line3 => 1.
<?php
//assuming the array keys represent line numbers
$my_array = array('1'=>$line1,'2'=>$line2,'3'=>$line3);
$pattern = '!(Sex|Fantasy|Porn)!i';
$matches = array();
foreach ($my_array as $key=>$value){
if(preg_match($pattern,$value)){
$matches[]=$key;
}
}
print_r($matches);
?>
$lines = array($line1, $line2, $line3);
$flag = false;
foreach($lines as $line){
if (preg_match("/(Sex|Fantasy|Porn)/i", $line)){
$flag = true;
break;
}
}
unset($lines);
if($flag){
echo 1;
} else {
echo 2;
}
?>
You might convert it to a function:
function x(){
$args = func_get_args();
if(count($args) < 2)return false;
$regex = array_shift($args);
foreach($args as $line){
if(preg_match($regex, $line)){
return true;
}
}
return false;
}
Usage:
x("/(Sex|Fantasy|Porn)/i", $line1, $line2, $line3 /* , ... */);
$line = "Hollywood Sex Fantasy , Porn";
if ((preg_match("/(Sex|Fantasy|Porn)/i", $line) && (preg_match("/(Sex|Fantasy|Porn)/i", $line1) && (preg_match("/(Sex|Fantasy|Porn)/i", $line2))
{
echo 1;
}
else
{
echo 2;
}
Crazy example. Using preg_replace instead of preg_match :^ )
$lines = array($line1, $line2, $line3);
preg_replace('/(Sex|Fantasy|Porn)/i', 'nevermind', $lines, -1, $count);
echo $count ? 1 : 2;

match the first & last whole word in a variable

I use php preg_match to match the first & last word in a variable with a given first & last specific words,
example:
$first_word = 't'; // I want to force 'this'
$last_word = 'ne'; // I want to force 'done'
$str = 'this function can be done';
if(preg_match('/^' . $first_word . '(.*)' . $last_word .'$/' , $str))
{
echo 'true';
}
But the problem is i want to force match the whole word at (starting & ending) not the first or last characters.
Using \b as boudary word limit in search:
$first_word = 't'; // I want to force 'this'
$last_word = 'ne'; // I want to force 'done'
$str = 'this function can be done';
if(preg_match('/^' . $first_word . '\b(.*)\b' . $last_word .'$/' , $str))
{
echo 'true';
}
I would go about this in a slightly different way:
$firstword = 't';
$lastword = 'ne';
$string = 'this function can be done';
$words = explode(' ', $string);
if (preg_match("/^{$firstword}/i", reset($words)) && preg_match("/{$lastword}$/i", end($words)))
{
echo 'true';
}
==========================================
Here's another way to achieve the same thing
$firstword = 'this';
$lastword = 'done';
$string = 'this can be done';
$words = explode(' ', $string);
if (reset($words) === $firstword && end($words) === $lastword)
{
echo 'true';
}
This is always going to echo true, because we know the firstword and lastword are correct, try changing them to something else and it will not echo true.
I wrote a function to get Start of sentence but it is not any regex in it.
You can write for end like this. I don't add function for the end because of its long...
<?php
function StartSearch($start, $sentence)
{
$data = explode(" ", $sentence);
$flag = false;
$ret = array();
foreach ($data as $val)
{
for($i = 0, $j = 0;$i < strlen($val), $j < strlen($start);$i++)
{
if ($i == 0 && $val{$i} != $start{$j})
break;
if ($flag && $val{$i} != $start{$j})
break;
if ($val{$i} == $start{$j})
{
$flag = true;
$j++;
}
}
if ($j == strlen($start))
{
$ret[] = $val;
}
}
return $ret;
}
print_r(StartSearch("th", $str));
?>

Categories