Echo array with string as separator - php

I have the following code in PHP, which searches a file for lines containing a string:
<?php
echo "Results for: ";
echo ($_POST['query']);
echo "<br><br>";
$file = 'completed.db';
$searchfor = ($_POST['query']);
header('Content-Type: text/plain');
$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$pattern.*\$/m";
if(preg_match_all($pattern, $contents, $matches)){
echo "Found matches:\n";
echo implode("\n", $matches[0]);
}
else{
echo "No matches found";
}
?>
In the line, echo implode("\n", $matches[0]); in echos an array, separated by spaces. If I wanted to separate the items by a different string, say $entry = '<br>', how would you do it?
For example, if $matches was
one
two
three
Then, the command should echo:
one<br>two<br>three<br>

Just add the break tag to the string
echo implode("\n<br>", $matches[0]);
And one more to trail since implode only goes between.
echo "<br>";

The following code simply uses implode with a different first argument, bu also adds the separator to the end (as per specification)
$entry = '<br>';
echo implode($entry, $matches[0]).$entry;

Related

Getting first and third word from string if tenth is a specific word

I have a constantly updated URL .txt file and I would like to grab the first and third words from every line where the tenth word is "B738". The words are spearated with ':'
Example from the file, here is 1 line: (yes, it is 1 line)
RYR98G:1374442:First Last:PILOT::36.50552:-13.87929:31183:451:B738:438:LPFR:31000:LPMA:UK1:100:1:7010:::1:I:0:0:1:41:3:30:GCXO:+VFPS+/V/PBN/A1B1C1D1S1S2 DOF/190521 REG/EIEFF OPR/RYR PER/C RMK/TCAS:N0438F310 IXOL9V IXOLI DCT LATRU DCT VERAM Q205 PECKY UQ146 EPAKA EPAK1X:0:0:0:0:::20190521084125:215:30.121:1020:
I would like to grab the "RYR98G" and the "First Last" because the tenth word is B738
<?php
$text = file_get_contents('http://data.vattastic.com/vatsim-data.txt');
$lines = explode("\n", $text);
$skipped_content = implode("\n", array_slice($lines, 62));
echo nl2br($skipped_content);
?>
Something like this should do what you want:
foreach ($lines as $line) {
$words = explode(':', $line);
if (isset($words[9]) && $words[9] == 'B738') {
echo "First: $words[0]\nThird: $words[2]\n";
}
}
Output (for your sample line):
First: RYR98G
Third: First Last
Demo on 3v4l.org
<?php
$text = file_get_contents('http://data.vattastic.com/vatsim-data.txt');
$lines = explode(":", $text);
if( $lines[9] == "B738" ){
echo $lines[0]; //RYR98G
echo $lines[2]; //First Last
}
?>
Here the stript, you need to load the content of your txt, in a variable.
<?php
$input_lines = "RYR98G:1374442:First Last:PILOT::36.50552:-13.87929:31183:451:B738:438:LPFR:31000:LPMA:UK1:100:1:7010:::1:I:0:0:1:41:3:30:GCXO:+VFPS+/V/PBN/A1B1C1D1S1S2 DOF/190521 REG/EIEFF OPR/RYR PER/C RMK/TCAS:N0438F310 IXOL9V IXOLI DCT LATRU DCT VERAM Q205 PECKY UQ146 EPAKA EPAK1X:0:0:0:0:::20190521084125:215:30.121:1020:"; // example of line
$matches = array(); //Array
$search = preg_match_all('/(.*?):(.*?)/im', $input_lines, $matches); //regex matching
if($matches[1][9] == "B738") //target :)
{
print_r('B738 Found! <br />');
print_r('Item 1!'.$matches[1][0].'<br />');
print_r('Item 2!'.$matches[1][3].'<br />');
}
// Debug of your array. As you can see all items matched.
foreach ($matches[1] as $match) {
echo " Item: ".$i."<br />";
echo $match;
$i++;
}

How do I exclude a specific string from being filtered by PHP's sanitize filters?

So what I want to do is print out all the strings in an array, but seperate them with <p> tags.
I tried this:
echo filter_var( implode( "<p>", $matches[0]), FILTER_SANITIZE_SPECIAL_CHARS); echo "</p>";
but it results in
string1</p>string2</p>string3</p>
instead of
<p>string1</p> <p>string2</p> <p>string3</p>
Any thoughts?
EDIT:
if you need the actual full code, here you go:
<?php
$file = 'logfile.log';
$searchfor = $_POST['name'];
$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$pattern.*\$/m";
if(preg_match_all($pattern, $contents, $matches)){
echo "Found matches:\n";
echo filter_var( implode( "<p>", $matches[0]), FILTER_SANITIZE_SPECIAL_CHARS);
}
echo "</p>";
else{
echo "No matches found";
}
?>
You should use htmlspecialchars() for any arbitrary string that you want to safely display on your page, not filter_var().
Here's the complete solution:
foreach ($matches[0] as $str) {
echo '<p>'.htmlspecialchars($str).'</p>';
}
Or, if you really want an (ugly) one-liner:
echo implode('', array_map(function ($str) { return '<p>'.htmlspecialchars($str).'</p>'; }, $matches[0]));

Replacing a word in an output. php

<?php
$file = 'C:\wamp\www\Killboard\EPChernarus1\PhitLog.txt';
$searchfor = 'Chernarus';
header('Content-Type: text/html');
$contents = file_get_contents($file);
$contents = str_replace("(ArmA-AH.net)", "(DayZNorway.com)", $contents);
$pattern = preg_quote($searchfor, '/');
$contents = str_replace("DayZ Instance: 11", " Map: Chernarus ", $contents);
$pattern = "/^.*$pattern.*$/m";
$contents = str_replace("PKILL", "Player Killed", $contents);
$contents = str_replace("CLOG", "Combat Logged", $contents);
if(preg_match_all($pattern, $contents, $matches)){
echo "<strong>";
echo "<div style ='font:11px/21px Arial,tahoma,sans-serif;color:#2983CB'>Killboard Epoch Chernarus: <br>";
echo '', implode(" <br>", $matches[0]);
echo "</strong>";
}
else
{
echo "No kills yet. Looks like everyone is playing nice.";
}
?>
After much help on here, code now looks this ^
Now i am trying to include the code below.
So that it will rename the weapon classes to more userfriendly names.
I have included the two .php files its looking for, but i am unsure to where i place it and if it will even run like it is, wich i doubt.
Could someone
if ($line_type == 'kill') {
include("killfeed_weapon_classnames.php");
include("killfeed_weapon_cleannames.php");
$swap_key = array_search($line_varlist['weapon'], $wcn);
if($swap_key != false) { $line_varlist['weapon'] = $wn[$swap_key]; }
}
Before all of your preg matching and right after $contents use:
$contents = str_replace("(Arma-AH.net)", "(DayZNorway.com)", $contents);
Edited forgot the parenthesis and next question. I am not going to just give you the next part, but look at the example below and follow along this should help you achieve what you want for that next question.
$myArray = array("firstName" =>"sam", "secondName" => "billy", "thirdName" => "sally");
$nameKey = array_search("billy", $myArray);
echo $nameKey;
if($nameKey){
$myArray[$nameKey] = "Tom";
}
print_r($myArray);
<?php
$file = 'C:\wamp\www\Killboard\EPChernarus1\PhitLog.txt';
$searchfor = 'Chernarus';
header('Content-Type: text/html');
$contents = file_get_contents($file);
$contents = str_replace("(ArmA-AH.net)", "(DayZNorway.com)", $contents);
$pattern = preg_quote($searchfor, '/');
$contents = str_replace("DayZ Instance: 11", " Map: Chernarus ", $contents);
$pattern = "/^.*$pattern.*$/m";
$contents = str_replace("PKILL", "Player Killed", $contents);
$contents = str_replace("CLOG", "Combat Logged", $contents);
if(preg_match_all($pattern, $contents, $matches)){
echo "<strong>";
echo "<div style ='font:11px/21px Arial,tahoma,sans-serif;color:#2983CB'>Killboard Epoch Chernarus: <br>";
echo '', implode(" <br>", $matches[0]);
echo "</strong>";
}
else
{
echo "No kills yet. Looks like everyone is playing nice.";
}
?>
This is what i ended up doing, now its hardly pretty, but it works.
Now i need to get the results to show in descending order.
Any chance someone could help me with this?

Retrieve text from XML?

I want to get all words between XML tags from a array and the current outcome is:
Notice: Array to string conversion in ........ on line 84
Result is: Array
if(isset($_POST['send']))
{
echo "sync is started <br>";
$handle = fopen("XML/$file_name", "r");
if ($handle)
{
while (($line = fgets($handle)) !== false)
{
$keywords=array("series_title","series_type","series_episodes");
for ($i=0; $i < 3; $i++)
{
$pattern = "/<$keywords[$i]>(.*?)<\/keywords[$i]>/";
preg_match($pattern, $line, $matches);
echo "result is: " . $matches . "<br>";
}
}
}
else
{
$upload_text = "error";
}
$upload_text ="finished";
fclose($handle);
//unlink('XML/' . $file_name);
}
You should use SimpleXML to read the XML instead. Here is an example:
<?php
$string = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<myanimelist>
<anime>
<series_animedb_id>1143</series_animedb_id>
<series_title><![CDATA[.hack//Intermezzo]]></series_title>
<series_type>Special</series_type>
<series_episodes>1</series_episodes>
</anime>
<anime>
<series_animedb_id>299</series_animedb_id>
<series_title><![CDATA[.hack//Liminality]]></series_title>
<series_type>OVA</series_type>
<series_episodes>4</series_episodes>
</anime>
</myanimelist>
XML;
$result = simplexml_load_string($string);
foreach ($result->anime as $anime)
{
echo trim($anime->series_title), "\n";
echo $anime->series_type, "\n";
echo $anime->series_episodes, "\n";
echo "==========================\n\n";
}
Live DEMO.
In your case you would use simplexml_load_file, so your code would look like this:
<?php
$result = simplexml_load_file('your_file_path_here.xml');
foreach ($result->anime as $anime)
{
echo trim($anime->series_title), "\n";
echo $anime->series_type, "\n";
echo $anime->series_episodes, "\n";
}
Well, as you can read in the Official PHP Documentation, the optional preg_match third argument will be an array
matches
If matches is provided, then it is filled with the results of search.
$matches[0] will contain the text that matched the full pattern,
$matches1 will have the text that matched the first captured
parenthesized subpattern, and so on.
So simply change your :
echo "result is: " . $matches . "<br>";
to :
echo "result is: " . $matches[1] . "<br>";
Hope it helps
The value returned in the $matches parameter of the preg_match function is an array, the first element of which is the entire match, and the following elements are the capture groups (the parts between parentheses).
So, in your code, you'd only be interested in $matches[1]:
echo "result is: $matches[1]<br>";

find a specific word in external page

How to find a specific word in a external page using php ?
(dom or pregmatch, or what else ?)
example in foo.com source code with :
span name="abcd"
I want to check if the word abcd is in foo.com in php
if(preg_match('/span\s+name\=\"abcd\"/i', $str)) echo 'exists!';
To check if a string of characters exist:
<?php
$term = 'abcd';
if ( preg_match("/$term/", $str) ) {
// yes it does
}
?>
To check if that string exists as a word in its own right (ie, is not in the middle of a larger word) use word boundary matchers:
<?php
$term = 'abcd';
if ( preg_match("/\b$term\b/", $str) ) {
// yes it does
}
?>
For a case-insensitive search, add the i flag after the last slash in the regex:
<?php
$term = 'abcd';
if ( preg_match("/\b$term\b/i", $str) ) {
// yes it does
}
?>
$v = file_get_contents("http://foo.com");
echo substr_count($v, 'abcd'); // number of occurences
//or single match
echo substr_count($v, ' abcd ');
Here are other few ways to find specific word
<?php
$str = 'span name="abcd"';
if (strstr($str, "abcd")) echo "Found: strstr\n";
if (strpos($str, "abcd")) echo "Found: strpos\n";
if (ereg("abcd", $str)) echo "Found: ereg\n";
if (substr_count($str, 'abcd')) echo "Found: substr_count\n";
?>
$name = 'foo.php';
file_get_contents($name);
$contents=$pattern = preg_quote('abcd', '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
echo implode("\n", $matches[0]);
}
else{
echo "not exist word";
}

Categories