Grab data from text document - php

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];
}
}

Related

Extract some string from the URL

I have a URL, e.g:
https://www.example.com/my-product-name-display/ex/BYADE3323/wgsi?nfh3420000ooo2323nfnf/.
From the above URL, I want to extract my-product-name-display if this URL contains it, if not, I want the string after /ex/{BYADE3323} as below URL does not contain my-product-name-display.
https://www.example.com/ex/BYADE3323/wgsi?nfh3420000ooo2323nfnf/
I have tried below code:
`$url_param = "https://www.example.com/ex/BYADE3323/wgsi?nfh3420000ooo2323nfnf/";`
or
`$url_param = "https://www.example.com/my-product-name-display/ex/BYADE3323/wgsi?nfh3420000ooo2323nfnf/";`
$e_product_title = explode('.com/', $url_param);
if(isset($e_product_title)){
$product_title = $e_product_title[1];
//now explode the ex
$get_asin = explode('/ex/',$product_title);
$final_product_title = str_replace('-',' ',$get_asin[0]);
$get_asin_final = explode('/', $get_asin[1]);
$asin_v2 = $get_asin_final[0];
}
else{
$get_asin = explode('/ex/',$url_param);
print_r($get_asin);
}
echo $final_product_title." ".$asin_v2;
Thanks in advance.
You can explode() the string,
Check if my-product-name-display and BYADE3323 is in the array.
If present, find out BYADE3323's index.
Add 1 to it and check if the next element is present.
<?php
$str = 'https://www.example.com/my-product-name-display/ex/BYADE3323/wgsi?nfh3420000ooo2323nfnf/';
$str = str_replace('://', '__', $str);
$arr = explode('/', $str);
$return = '';
if (in_array('my-product-name-display', $arr) && in_array('BYADE3323', $arr)) {
$idx = array_search('BYADE3323', $arr);
$idx2 = $idx + 1;
if (! empty($idx) && ! empty($arr[$idx2])) {
$idx += 1;
$return = $arr[$idx2];
}
}
echo $return;
EDIT:
As per comments from OP, following is the program for array of urls and array of search strings.
<?php
$searchStrings = [];
$searchStrings[] = ['my-product-name-display', 'BYADE3323'];
$searchStrings[] = ['your-product-name-display', 'BYADE4434'];
$urls = [];
$urls[] = 'https://www.example.com/my-product-name-display/ex/BYADE3323/wgsi?nfh3420000ooo2323nfnf/';
$urls[] = 'https://www.example.com/your-product-name-display/ex/BYADE4434/wgsi?nfh3420000ooo2323nfnf/';
$urls[] = 'https://www.example.com/their-product-name-display/ex/TEST343/wgsi?nfh3420000ooo2323nfnf/';
$urls[] = 'https://www.example.com/my-product-name-display/ex/ANASDF33/wgsi?nfh3420000ooo2323nfnf/';
$urls[] = 'https://www.example.com/my-product-name-display/ex/BYADE3323/wgsi?nfh3420000ooo2323nfnf/';
$return = [];
if (! empty($urls)) {
foreach ($urls as $url) {
if (! empty($searchStrings)) {
foreach ($searchStrings as $searchString) {
$str = implode('/ex/', $searchString);
if (strpos($url, $str) !== false) {
$arr = explode('/', $url);
$idx = array_search('BYADE3323', $arr);
$idx2 = $idx + 1;
if (! empty($idx) && ! empty($arr[$idx2])) {
$idx += 1;
$return[] = $arr[$idx2];
}
}
}
}
}
}
echo '<pre>';
print_r($return);
echo '</pre>';
Output:
Array
(
[0] => wgsi?nfh3420000ooo2323nfnf
[1] => wgsi?nfh3420000ooo2323nfnf
)
Try this to fetch from URL values.
pass url to the function. You can extract it.
Here is the URL :
https://www.example.com/my-product-name-display/ex/BYADE3323/wgsi?nfh3420000ooo2323nfnf/
So when u want only BYADE3323 this value.
When you print $parts array, you can find every values after your Host name.
Where your host name is https://www.example.com.
function GetStringAfterSecondSlashInURL($the_url)
{
$parts = explode("/",$the_url,3);
if(isset($parts[2]))
return $parts[2];
}
Use parse_url() function this will help you definitely.
You can refer it from official PHP site: parse-url.
You can use strpos to identify weather 'my-product-name-display' is exist s in url or not and execute code accordingly.
strpos($url_param, 'my-product-name-display') !== false
Modified code:
function get_product_title($url_param) {
$get_asin = explode('/ex/', $url_param);
$get_asin_final = explode('/', $get_asin[1]);
$asin_v2 = $get_asin_final[0];
return $asin_v2;
}
$url_param = "https://www.example.com/ex/BYADE3323/wgsi?nfh3420000ooo2323nfnf/";
$url_param = "https://www.example.com/my-product-name-display/ex/BYADE3323/wgsi?nfh3420000ooo2323nfnf/";
$product_name = '';
if (strpos($url_param, 'my-product-name-display') !== false) {
$e_product_title = explode('.com/', $url_param);
if (isset($e_product_title)) {
$product_title = $e_product_title[1];
//now explode the ex
$product_name = get_product_title($product_title);
}
echo "my product name display" . $product_name;
}
else {
$product_name = get_product_title($url_param);
echo $product_name;
}

how to find a value contained inside a value inside an array?

If I have the array:
$os = array("Mac", "NT", "Irix", "Linux");
I know that in_array() is what to use if I want to find "Mac" inside $os.
But what I have the array:
$os = array( [1] => "Mac/OSX", [2] => "PC/Windows" );
and I want to see if "Mac" is contained in $os?
Try:
$example = array("Mac/OSX","PC/Windows" );
$searchword = 'Mac';
$matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", $var); });
You could also use array_map to do this. Take a look at the following code:
$array = array(
'Mac/OSX',
'PC/Windows',
);
$result = in_array(true, array_map(function ($word, $match, $char = "/") {
$words = explode('/', $word);
return in_array($match, $words) ? true : false;
}, $array, array('Mac')));
var_dump($result); // bool(true)
You can try this-
$os = array( "Mac/OSX", "PC/Windows" );
function findInArray($os){
foreach($os as $val){
if(strpos($val, $word_to_search) !== false){
return true;
}
}
return false;
}
Here is another solution:
array_map(function($v){
if (strpos($v, 'Mac') !== false) {
echo 'found';
exit;
}
},$os);
echo "Not found";
DEMO
You can simply use preg_grep function of PHP like as
$os = array( '1' => "Mac/OSX", '2' => "PC/Windows" );
print_R(preg_grep("/Mac/",$os));
Output:
Array ( [1] => Mac/OSX )
By using foreach and strpos
$os =array("Mac/OSX","PC/Windows" );
$string = "Mac";
foreach ($os as $data) {
//echo $data;
if (strpos($data,$string ) !== FALSE) {
echo "Match found";
}else{
echo "not found";
}
}
DEMO
function FindString($string, $os)
{
// put the string in between //
$preg = "/$string/";
// Match found
$found = false;
// loop each value
for($j = 0; $j < count($os); $j++)
{
// check with pattern
if(preg_match($preg,$os[$j]))
{
// set var to ture
$found = true;
// Break
break;
}
}
if($found == false)
{
die("Unable to found the string $string.");
}
echo "String $string found in array index $j and value is $os[$j]";
}
$where =array("Mac/OSX","PC/Windows" );
$what = "Mac";
FindString($what, $where);

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'];

PHP, Match line, and return value

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.

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;

Categories