How Do I replace Specific Text in PHP - php

I have some data in the following format.
Orange - $3.00
Banana - $1.25
I would like to print this as only as follows:
Orange
Banana
I tried using following code in a loop but the data may have 0 in other places as well. So if I can find 0 only at the end for a specific line.
$pos=strpos($options, "0");
$options = substr($options, 0, $pos)."\n";
Any ideas?

Is this what you're looking for?
<?php
$input = 'Orange - $3.00';
list($fruit, $price) = explode('-', $input);
?>
Or if you want to proces all the input:
<?php
$input = 'Orange - $3.00
Banana - $1.25';
$fruitlist = array();
$sepLines = explode("\n", $input);
foreach($seplines as $line)
{
list($fruit, $price) = explode(' - ', $line);
$fruitlist[] = $fruit;
}
?>

Are you trying to print only the name of the item and not the price?
$n=explode(" - ", "Banana - $1.25");
print $n[0];

$string = explode("-", $originalText);
$word = $string[0];
and thats it :)

Related

Trying to fix SKU numbers from 55A_3 to A55_3 with PHP in SQL

I have SKU numbers imported from a CSV file into SQL DB.
Pattern look like:
55A_3
345W_1+04B_1
128T_2+167T_2+113T_8+115T_8
I am trying to move all the letters in front of the numbers.
like:
A55_3
W345_1+B04_1
T128_2+T167_2+T113_8+T115_8
My best idea how to do it was to search for 345W and so, and to replace it with W345 and so:
$sku = "345W_1+04B_1";
$B_range_num = range(0,400);
$B_range_let = range("A","Z");
then generating the find and replace arrays
$B_find =
$B_replace =
maybe just using str_replace??
$res = str_replace($B_find,$B_replace,$sku);
Result should be for all SKU numbers
W345_1+B04_1
Any ideas?
You can use preg_replace to do this job, looking for some digits, followed by a letters and one of an _ with digits, a + or end of string, and then swapping the order of the digits and letters:
$skus = array('55A_3',
'345W_1+04B_1',
'128T_2+167T_2+113T_8+115T_8',
'55A');
foreach ($skus as &$sku) {
$sku = preg_replace('/(\d+)([A-Z]+)(?=_\d+|\+|$)/', '$2$1', $sku);
}
print_r($skus);
Output:
Array
(
[0] => A55_3
[1] => W345_1+B04_1
[2] => T128_2+T167_2+T113_8+T115_8
[3] => A55
)
Demo on 3v4l.org
Here I defined a method with specific format with unlimited length.
$str = '128T_2+167T_2+113T_8+115T_8';
echo convertProductSku($str);
function convertProductSku($str) {
$arr = [];
$parts = explode('+', $str);
foreach ($parts as $part) {
list($first, $second) = array_pad(explode('_', $part), 2, null);
$letter = substr($first, -1);
$number = substr($first, 0, -1);
$arr[] = $letter . $number . ($second ? '_' . $second : '');
}
return implode('+', $arr);
}

Filter on hight of number in textfile

ive been trying this by splitting the lines with substring and than using array unique on it but I cant get it to work properly. the idea is... if the same line is in the file with a lower number... keep the line with the higher number.
textfile:
wood tiger 22324 Squirrel
john apple 24574 Squirrel
peter snuggle 21234 Squirrel
james coolest 20108 Squirrel
james coolest 20134 Squirrel
output needed:
wood tiger 22324 Squirrel
john apple 24574 Squirrel
peter snuggle 21234 Squirrel
james coolest 20134 Squirrel
so it basically has to keep the highest numbered item if its the same line (the higher the number the newer the line is).
What I've tried so far:
$file_handle = fopen("file.txt", "rb" , FILE_SKIP_EMPTY_LINES);
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
if ($line_of_text[0] === ' ') continue;
if ($line_of_text[0] === ' ') continue;
$part1 = substr("$line_of_text", ..., ...);
$part2 = substr("$line_of_text", ..., ...);
$part3 = substr("$line_of_text", ..., ...);
$part1 = explode(' ', $part1);
$part1 = array_unique($part1);
$part1 = implode(' ', $part1);
var_dump ($part1);
}
file_put_contents('outputfile.txt', implode(PHP_EOL, $lines));
?>
Keep track of your "final" values in an associative array as you loop through the file. Compare each row to the array before adding it to avoid duplicates.
<?php
$file_handle = fopen("test.csv", "rb" , FILE_SKIP_EMPTY_LINES);
$finalArray = array();
$numberPartCol = 1;
while (($line_of_text = fgets($file_handle))) {
if ($line_of_text[0] === ' ') continue;
// why check the same thing twice?
// going to assume you have this part working as you didn't ask about it
$uniqueKeyPart = substr("$line_of_text", ..., ...);
// remove all the spaces so we can compare the numbers
$numberPart = str_replace(" ", "", substr("$line_of_text", ..., ...));
$squirrelPart = substr("$line_of_text", ..., ...);
if(!array_key_exists($uniqueKeyPart, $finalArray)) {
$finalArray[$uniqueKeyPart] = array(
// use preg_replace to get rid of all the extra whitespace
// if you don't want the spaces at all, just use str_replace as above
preg_replace("/ +/", " ", $uniqueKeyPart),
$numberPart,
preg_replace("/ +/", " ", $squirrelPart)
);
}
else {
if($finalArray[$uniqueKeyPart][$numberPartCol] < $numberPart) {
$finalArray[$uniqueKeyPart][$numberPartCol] = $numberPart;
}
}
}
// loop through $finalArray to put the data in the format you want for the outputfile.txt
$lines = array();
foreach($finalArray as $row) {
$lines = implode(",", $row) . PHP_EOL;
}
file_put_contents('outputfile.txt', $lines);
?>
fgetcsv()
Please do consider changing how the data is stored in the first place. My sympathies if you have no control over that :(

Get two different arrays from a textfield form

I have a single textarea input in my html form.
Users will write in that textarea like this:
5x Blue Flower
2 Red Flower
3* Yellow Flower
Purple Flower
So i need to get two arrays from this. One is a number and the other is the flower.
For now i got the numbers in array but i am struggling with getting only flowers in the second array.
Also, where they don't put a number, there should be a default number 1.
$text_data = $_POST['tekst'];
$input = explode("\n", $text_data);
foreach($input as $line)
{
$number = preg_replace("/[^0-9]/", '', $line);
echo $number . '<br>';
echo $line;
}
Any help would be much appreciated.
Try
foreach($input as $line){
preg_match("/\d+/", $line, $matches);
$line = preg_replace("/\d+/",'' ,$line);
$number = (isset($matches[0]))?$matches[0]:1;
if(strlen($line)>0){
echo $number."-->".$line."\n";
}
}
See demo here

Filter array or string(removing some words)

My problem is not very complex but I can't find a solution yet. I have a string:
$temp_string = '20938999038,0.5,83888999289,0.5,98883888778,0.9';
// Meaning syskey, price, syskey, price, syskey, price
I want to remove price and show only syskey.
My desirable result:
'20938999038,83888999289,98883888778'
Thanks in advance.
You can explode it by delimiter
$explode = explode(",", $temp_string);
unset($explode[1], $explode[3], $explode[5]);
Assuming your string always follows this pattern.
You can try:
$string = "20938999038,0.5,83888999289,0.5,98883888778,0.9";
$new = array();
foreach(explode(",", $string) as $k => $v) {
$k % 2 or $new[] = $v;
}
echo implode(",", $new); // 20938999038,83888999289,98883888778

Content segregation from a Text string

I have this "&params=&offer=art-by-jeremy-johnson" stored in my data base.
Is there any function / method to get the output as "Art by Jeremy Johnson" using the above as the input value. this should be changed to the output "Art by Jeremy Johnson" only on the runtime.
can this be done in PHP.
Please help.
$orig = '&params=&offer=art-by-jeremy-johnson';
$parts = explode('=', $orig);
$output = explode('-', end($parts));
echo ucwords(implode(' ', $output));
In Java, I guess you can just use lastIndexOf to get the last index of the equals sign, and get the remainder of the string (using substring).
if (myString.lastIndexOf("=") != -1) {
String words = myString.substring(myString.lastIndexOf("=")+1);
words.replaceAll("-", " ");
return words;
}
$string="&params=&offer=art-by-jeremy-johnson";
parse_str($string,$output);
//print_r($output);
$str=ucwords(str_replace("-"," ",$output['offer']));
If I understand well you want to not capitalized some words.
Here is a way to do it :
$str = "&params=&offer=art-by-jeremy-johnson";
// List of words to NOT capitalized
$keep_lower = array('by');
parse_str($str, $p);
$o = explode('-', $p['offer']);
$r = array();
foreach ($o as $w) {
if (!in_array($w, $keep_lower))
$w = ucfirst($w);
$r[] = $w;
}
$offer = implode(' ', $r);
echo $offer,"\n";
output:
Art by Jeremy Johnson

Categories