Backreference preg_replace with commas in subject - php

Can you please help me find the preg_replace syntax so i can duplicate the price where it is missing?
The subject is:
...nomaterwhat13124123,"321,00",,nomaterwhat
...nomaterwhat12321,"322,20","134,00",nomaterwhat
...nomaterwhat1321,"211,00",,nomaterwhat
...nomaterwhat31313,"241,00",,nomaterwhat
My output want to be:
...nomaterwhat13124123,"321,00","321,00",nomaterwhat
...nomaterwhat12321,"322,20","134,00",nomaterwhat
...nomaterwhat1321,"211,00","211,00",nomaterwhat
...nomaterwhat31313,"241,00","241,00",nomaterwhat
I tried
preg_replace("(\W+),,nomaterwhat$", "$1,$1,nomaterwhat", $string);

Ignoring more complex cases this should do:
$result = preg_replace('/,"(\d+,\d{2})",,nomaterwhat/', ',"$1",$1,nomaterwhat', $string);

If you use str_getcsv you can do something like this:
$data = "CSV VALUES";
$lines = explode("\n", $data);
foreach ($lines as $line) {
$temp = str_getcsv($line);
echo '<pre>' . print_r($temp, true) . '</pre>';
}
Then you can put these into an array like so:
$data = "CSV VALUES";
$lines = explode("\n", $data);
$output = array();
foreach ($lines as $line) {
$temp = str_getcsv($line);
$temp[5] = ($temp[5] == '') ? $temp[4] : $temp[5];
$output[] = $temp;
}
echo '<pre>' . print_r($output, true) . '</pre>';
Replace $temp[5] with the place that the 2nd price should be.

You have a few issues with your regex.
1. No delimiter
2. No m modifier so $ is the end of the string, not line.
3. \W+ is a non a-z, 0-9, and/or _ so you wouldn't have gotten the
money value there anyway.
Try this out:
$string = '...nomaterwhat13124123,"321,00",,nomaterwhat
...nomaterwhat12321,"322,20","134,00",nomaterwhat
...nomaterwhat1321,"211,00",,nomaterwhat
...nomaterwhat31313,"241,00",,nomaterwhat';
echo preg_replace("/,(\"\d+,\d{2}\"),,nomaterwhat$/m", ",$1,$1,nomaterwhat", $string);
Output:
...nomaterwhat13124123,"321,00","321,00",nomaterwhat
...nomaterwhat12321,"322,20","134,00",nomaterwhat
...nomaterwhat1321,"211,00","211,00",nomaterwhat
...nomaterwhat31313,"241,00","241,00",nomaterwhat
Regex Demo: https://regex101.com/r/hE2zQ7/1
PHP Demo: http://ideone.com/OanPN1

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

Read fails with spaces

I am very new to PHP and want to learn. I am trying to make a top-list for my server but I have a problem. My file is built like this:
"Name" "Kills"
"^0user1^7" "2"
"user2" "2"
"user3" "6"
"user with spaces" "91"
But if I want to read this with PHP it fails because the user has spaces.
That's the method I use to read the file:
$lines = file('top.txt');
foreach ($lines as $line) {
$parts = explode(' ', $line);
echo isset($parts[0]) ? $parts[0] : 'N/A' ;
}
Maybe someone knows a better method, because this don't work very well :D.
You need REGEX :-)
<?php
$lines = array(
'"^0user1^7" "2"',
'"user2" "2"',
'"user3" "6"',
'"user with spaces" "91"',
);
$regex = '#"(?<user>[a-zA-Z0-9\^\s]+)"\s"(?<num>\d+)"#';
foreach ($lines as $line) {
preg_match($regex, $line, $matches);
echo 'user = '.$matches['user'].', num = '.$matches['num']."\n";
}
In the regex, we have # delimiters, then look for stuff between quotes. Using (?PATTERN) gives you a named capture group. The first looks for letters etc, the second digits only.
See here to understand how the regex is matching!
https://regex101.com/r/023LlL/1/
See it here in action https://3v4l.org/qDVuf
For your process this might help
$lines = file('top.txt');
$line = explode(PHP_EOL, $lines); // this will split file content line by line
foreach ($line as $key=>$value_line ) {
echo str_replace(" ","",$value_line);
}
As I commented above, below is a simple example with JSON.
Assuming, you have stored records in JSON format:
$json = '{
"user1": "12",
"sad sad":"23"
}';
$decoded = json_decode($json);
foreach($decoded as $key => $value){
echo 'Key: ' . $key . ' And value is ' . $value;
}
And here is the demo link: https://3v4l.org/ih1P7

Get value from file - php

Let's say I have this in my text file:
Author:MJMZ
Author URL:http://abc.co
Version: 1.0
How can I get the string "MJMZ" if I look for the string "Author"?
I already tried the solution from another question (Php get value from text file) but with no success.
The problem may be because of the strpos function. In my case, the word "Author" got two. So the strpos function can't solve my problem.
Split each line at the : using explode, then check if the prefix matches what you're searching for:
$lines = file($filename, FILE_IGNORE_NEW_LINES);
foreach($lines as $line) {
list($prefix, $data) = explode(':', $line);
if (trim($prefix) == "Author") {
echo $data;
break;
}
}
Try the following:
$file_contents = file_get_contents('myfilename.ext');
preg_match('/^Author\s*\:\s*([^\r\n]+)/', $file_contents, $matches);
$code = isset($matches[1]) && !empty($matches[1]) ? $matches[1] : 'no-code-found';
echo $code;
Now the $matches variable should contains the MJMZ.
The above, will search for the first instance of the Author:CODE_HERE in your file, and will place the CODE_HERE in the $matches variable.
More specific, the regex. will search for a string that starts with the word Author followed with an optional space \s*, followed by a semicolon character \:, followed by an optional space \s*, followed by one or more characters that it is not a new line [^\r\n]+.
If your file will have dinamically added items, then you can sort it into array.
$content = file_get_contents("myfile.txt");
$line = explode("\n", $content);
$item = new Array();
foreach($line as $l){
$var = explode(":", $l);
$value = "";
for($i=1; $i<sizeof($var); $i++){
$value .= $var[$i];
}
$item[$var[0]] = $value;
}
// Now you can access every single item with his name:
print $item["Author"];
The for loop inside the foreach loop is needed, so you can have multiple ":" in your list. The program will separate name from value at the first ":"
First take lines from file, convert to array then call them by their keys.
$handle = fopen("file.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$pieces = explode(":", $line);
$array[$pieces[0]] = $pieces[1];
}
} else {
// error opening the file.
}
fclose($handle);
echo $array['Author'];

How to remove unwanted commas from a string?

How can i remove duplicate commas used in string.
String = ",a,b,c,,,d,,"
I tried rtrim and itrim functions and removed the unwanted commas from beginning and ending .How can i remove duplicate commas ?
Try this:
$str = preg_replace('/,{2,}/', ',', trim($str, ','));
The trim will remove starting and trailing commas, while the preg_replace will remove duplicate ones.
See it in action!
Also, as #Spudley suggested, the regex /,{2,}/ could be replaced with /,,+/ and it would work too.
EDIT:
If there are spaces between commas, you may try adding the following line after the one above:
$str = implode(',', array_map('trim', explode(',', $str)))
i think you can just explode your string and then create a new one getting only relevant data
$string = ",a,b,c,,,d,,";
$str = explode(",", $string);
$string_new = '';
foreach($str as $data)
{
if(!empty($data))
{
$string_new .= $data. ',';
}
}
echo substr_replace($string_new, '', -1);
This will output
a,b,c,d
Live Demo
EDITED
If you are having problems with blank spaces you can try use this code
$string = ",a,b,c, ,,d,,";
$str = explode(",", str_replace(' ', '', $string));
$string_new = '';
foreach($str as $data)
{
if(!empty($data))
{
$string_new .= $data. ',';
}
}
echo substr_replace($string_new, '', -1);
This should solve spaces issue
Probably not very fast, but a simple method may be:
$str = "a,b,c,,,d";
$str2 = "";
while($str <> $str2) {
$str2 = $str;
$str = str_replace(',,', ',', $str);
}
<?php
$str = ",a,b,c,,,d,,"
echo $str=str_replace(',,','',$str);
?>
Output:
,a,b,c,d
<?php
$str = ",a,b,c,,,d,,"
echo $str=trim(str_replace(',,','',$str),',');
?>
Output:
a,b,c,d

How to wrap string in span before and after all newlines in PHP?

Upon searching I found PHP function that do inserts before all newlines in a string which is
nl2br();
example:
<?php
echo nl2br("This is an example\r\n where line breaks\r\n added", false);
?>
Above code Output :
This is an example<br\>
where line breaks<br\>
added
What I wanted to have output instead of <br/> I will wrap the string with the tags before and after all newlines
example output from code above wrap string with span
<span>This is an example</span>
<span>where line breaks</span>
<span>added</span>
Is there PHP function exist to this? or a custom PHP function
$str = "This is an example\r\n where line breaks\r\n added";
$str = explode("\r\n",$str);
foreach($str as $key => $value) {
echo "<span>".$value."</span>";
}
You could do an "explode" on "\r\n" and loop over each value with a concatenated span.
Something like
$values = explode("\r\n", "one\r\ntwo\r\nthree\r\nfour")
$newvalues = ""
foreach($values as $value){
$newvalues = $newvalues . "<span>" . $value . "</span>"
}
Use file(). It will return the entire file as an array, each being a new line. Iterate through there and add your span's. Not the best way, but if you have a lot of files to do this for, it's just as easy as any other solution. Otherwise, just explode on your delimiter.
function splitToSpans($string) {
$lines = explode('\r\n', $string);
$finalString = '';
foreach ($lines as $line) {
$finalString .= '<span>' . $line . '</span>';
}
return $finalString;
}
Something like:
$strout = '';
$lines = explode(PHP_EOL, $input);
foreach ($lines as $line) {
$strout .= "<span>$line</span>";
}
Option 1:
<?php
$string = "Line 1
Line 2
Line 3";
$string = preg_replace('/^(.*)$/m', '<span>$1</span>', $string);
echo $string;
Option 2:
<?php
$string = "Line 1\r\nLine 2\r\nLine 3";
$string = array_map(function($value) {
return "<span>$value</span>";
}, explode("\r\n", $string));
echo implode("\r\n", $string);
This function splits the string based on either a CRLF or LF only and then wraps it into a <span> tag, applying proper escaping (important):
function nl2span($str)
{
$r = '';
foreach (preg_split("/\r?\n/", $str) as $line) {
$r .= '<span>' . htmlspecialchars($line). '</span>';
}
return $r;
}
If your line endings are always CRLF you can replace the preg_split() with a more conventional explode("\r\n", ...).
$string = "This is an example\r\n where line breaks\r\n added";
var_dump($string);
// string(46) "This is an example
// where line breaks
// added"
array_map(function($s){echo sprintf('<span>%s</span>', trim($s));}, explode("\r\n", $string));
// <span>This is an example</span>
// <span>where line breaks</span>
// <span>added</span>
This is useful:
function nl2span( $str) {
return '<span>' . implode( '</span><span>', explode( "\r\n", $str ) ) . '</span>';
}
Read through the answers, and noone had mentioned this solution...
$string = "This is an example\r\n where line breaks\r\n added";
echo '<span>' . str_replace('\r\n', '</span><span>', $string) . '</span>';

Categories