PHP Form implode / explode - php

I am using the a db field merchant_sku_item in a form. the original value is separated by / in the db like this:
2*CC689/1*CC368-8/1*SW6228-AB
I want to display in a text area on each line so I tried like this:
<textarea name="merchant_sku_item" rows="5" class="form-control" id="merchant_sku_item"><?
$items=explode('/',$merchant_sku_item);
foreach($items as $item){
echo $item."\r\n";
}
?></textarea>
All works fine:
2*CC689
1*CC368-8
1*SW6228-AB
but when I post the form I get a value like this:
2*CC689 1*CC368-8 1*SW6228-AB
but I wan't it back in the original format to update the DB in the correct format:
2*CC689/1*CC368-8/1*SW6228-AB
I tried to implode it with the / but I think it's just one string now so it's not working. I could replace the spaces I guess but this will not work if the field contains spaces.
Could somebody please tell me the best way to handle this?

The explode is correct, but you cannot just echo $item . "\r\n" because if $item contains </textarea> or whatever HTML you'll skrew up the page. You have to use echo htmlspecialchars($item) . "\n";. Normally, HTML pages have Linux line endings with "\n" and not Windows line endings with "\r\n".
To re-create the value for the DB, you have to take in consideration that the user may add some spaces or new lines. So you might not just get "\r\n" between the values but also " \n" or I don't know what. This is why a regular expression will be more flexible than a simple explode().
The regular expression pattern: \s+
The pattern \s will match any space, tab or new line chars. If you add the + sign after, it means that it can be 1 or multiple times. So this means that " \r\n" will match as it contains spaces, a carriege return and a new line. In PHP, you put the pattern between a delimiter char that you choose and that you put at the begin and the end. Commonly it's a slash so it becomes /\s+/. But you sometimes see also #\s+# or ~\s+~. After this delimiter, you can put some flags to change the way the regular expression is executed. Typically /hello/i will match "Hello" or "hello" because the i flag makes the search case-insensitive.
Similar to what you did: explode and re-implode example:
<?php
// Example of values that could be posted because users are always
// stupid and add spaces that they then don't see anymore.
$examples = [
"2*CC689 1*CC368-8 1*SW6228-AB", // spaces
"2*CC689\n1*CC368-8\n1*SW6228-AB", // new lines
"2*CC689\r\n1*CC368-8\r\n1*SW6228-AB", // carriege returns and new lines
"2*CC689\n 1*CC368-8 \n1*SW6228-AB", // new lines and spaces
];
foreach ($examples as $merchant_sku_item) {
$values = preg_split('/\s+/', $merchant_sku_item);
$merchant_sku_item_for_db = implode('/', $values);
echo $merchant_sku_item_for_db . "\n";
}
?>
Output:
2*CC689/1*CC368-8/1*SW6228-AB
2*CC689/1*CC368-8/1*SW6228-AB
2*CC689/1*CC368-8/1*SW6228-AB
2*CC689/1*CC368-8/1*SW6228-AB
Simplier, you could also just do a replacement with the same regular expression like this:
<?php
// Example of values that could be posted.
$examples = [
"2*CC689 1*CC368-8 1*SW6228-AB", // spaces
"2*CC689\n1*CC368-8\n1*SW6228-AB", // new lines
"2*CC689\r\n1*CC368-8\r\n1*SW6228-AB", // carriege returns and new lines
"2*CC689\n 1*CC368-8 \n1*SW6228-AB", // new lines and spaces
];
foreach ($examples as $merchant_sku_item) {
$merchant_sku_item_for_db = preg_replace('/\s+/', '/', $merchant_sku_item);
echo $merchant_sku_item_for_db . "\n";
}
?>
And just another important point regarding the data the user could input: What happens if the user types "2*CC/689" in the textarea?
Well, this will break your DB value :-/
This means that you have to validate the user input with some checks:
<?php
header('Content-Type: text/plain');
$examples = [
"2*CC689 1*CC368-8 1*SW6228-AB", // spaces
"2*CC689\n1*CC368-8\n1*SW6228-AB", // new lines
"2*CC689\r\n1*CC368-8\r\n1*SW6228-AB", // carriege returns and new lines
"2*CC689\n 1*CC368-8 \n1*SW6228-AB", // new lines and spaces
// Test with invalid datas:
"2*C/C689\n1*CC368-8\n1*SW6228-AB", // slash not allowed
"*CC689\n1*CC368-8\n1*SW6228-AB", // missing number before the *
"1*\n1*CC368-8\n1*SW62?28-AB", // missing product identifier and invalid ?
"1CC689 1*CC368-8 1SW6228-AB", // missing *
];
foreach ($examples as $example_nbr => $merchant_sku_item) {
echo str_repeat('=', 80) . "\n";
echo "Example $example_nbr\n\$merchant_sku_item = \"$merchant_sku_item\"\n";
$values = preg_split('/\s+/', $merchant_sku_item);
$errors = [];
foreach ($values as $i => $value) {
echo "Value $i = \"$value\"";
// Pattern: a number followed by * and followed by a product id (length between 3 and 10).
if (!preg_match('/^\d+\*[\d\w-]{3,10}$/i', $value)) {
echo " <-- ERROR\n";
$errors[] = $value;
} else {
echo "\n"; // It's ok
}
}
if (!empty($errors)) {
// You should handle the error and reload the form with the posted value and an error
// message explaining to the user what format is allowed.
echo "ERROR: Cannot save the value because the following products are wrong:\n";
echo implode("\n", $errors) . "\n";
}
}
?>
Test it here: https://onecompiler.com/php/3xtff6nk8

You can use preg_replace for your final post string like below code
$str = "2*CC689 blue 1*CC368-8 red 1*SW6228-AB";
$items = preg_replace('/\s+/', '/', $str);
echo $items;
output
2*CC689/blue/1*CC368-8/red/1*SW6228-AB
I Hope understand your question exactly.

Try replacing the created spaces and removing newline characters like so:
<?php
$merchant_sku_item = str_replace("\r\n","/",trim($_POST["merchant_sku_item"]));
?>

Make it this way:
<textarea name="merchant_sku_item" rows="5" class="form-control" id="merchant_sku_item"><?
$items=explode('//',$merchant_sku_item);
foreach($items as $item){
echo $item."\r\n";
}
?></textarea>

Related

PHP extra whitespace not being deleted

I'm counting words in an article and removing common words such as "and" or "the".
I"m removing them by use of preg_replace
after it is done I do a quick clean of extra white space by using.
$search_body = preg_replace('/\s+/',' ',$search_body);
However I've got some very stubborn white space that will not go away. I've tried
if($word == "" OR $word == " "){
//chop it's head off
}
But the if statement does not see $word as being just whitespace. I've also tried printing it to the screen to get the raw data type of it and it's still just showing up blank.
Here is the full regex that I'm using.
$pattern = array(
'/\&quot\;/',
'/[0-9]/',
'/\,/',
'/\./',
'/\!/',
'/\#/',
'/\#/',
'/\$/',
'/\%/',
'/\^/',
'/\&/',
'/\*/',
'/\(/',
'/\)/',
'/\_/',
'/\"/',
'/\'/',
'/\:/',
'/\;/',
'/\?/',
'/\`/',
'/\~/',
'/\[/',
'/\]/',
'/\{/',
'/\}/',
'/\|/',
'/\+/',
'/\=/',
'/\-/',
'/–/',
'/°/',
'/\bthe\b/',
'/\band\b/',
'/\bthat\b/',
'/\bhave\b/',
'/\bfor\b/',
'/\bnot\b/',
'/\bwith\b/',
'/\byou\b/',
'/\bthis\b/',
'/\bbut\b/',
'/\bhis\b/',
'/\bfrom\b/',
'/\bthey\b/',
'/\bsay\b/',
'/\bher\b/',
'/\bshe\b/',
'/\bwill\b/',
'/\bone\b/',
'/\ball\b/',
'/\bwould\b/',
'/\bthere\b/',
'/\btheir\b/',
'/\bwhat\b/',
'/\bout\b/',
'/\babout\b/',
'/\bwho\b/',
'/\bget\b/',
'/\bwhich\b/',
'/\bwhen\b/',
'/\bmake\b/',
'/\bcan\b/',
'/\blike\b/',
'/\btime\b/',
'/\bjust\b/',
'/\bhim\b/',
'/\bknow\b/',
'/\btake\b/',
'/\bpeople\b/',
'/\binto\b/',
'/\byear\b/',
'/\byour\b/',
'/\bgood\b/',
'/\bsome\b/',
'/\bcould\b/',
'/\bthem\b/',
'/\bsee\b/',
'/\bother\b/',
'/\bthan\b/',
'/\bthen\b/',
'/\bnow\b/',
'/\blook\b/',
'/\bonly\b/',
'/\bcome\b/',
'/\bits\b/', //it's?
'/\bover\b/',
'/\bthink\b/',
'/\balso\b/',
'/\bback\b/',
'/\bafter\b/',
'/\buse\b/',
'/\btwo\b/',
'/\bhow\b/',
'/\bour\b/',
'/\bwork\b/',
'/\bfirst\b/',
'/\bwell\b/',
'/\bway\b/',
'/\beven\b/',
'/\bnew\b/',
'/\bwant\b/',
'/\bbecause\b/',
'/\bany\b/',
'/\bthese\b/',
'/\bgive\b/',
'/\bday\b/',
'/\bmost\b/',
'/\bare\b/',
'/\bwas\b/',
'/\<\w+\>/', '/\<\/\w+\>/',
'/\b\w{1}\b/', //1 letter word
'/\b\w{2}\b/', //2 letter word
'/\//',
'/\</',
'/\>/'
);
$search_body = strip_tags($body);
$search_body = strtolower($search_body);
$search_body = preg_replace($pattern, ' ', $search_body);
$search_body = preg_replace('/\s+/',' ',$search_body);
$search_body = explode(" ", $search_body);
When exploded blank values show up left and right
Example text that I am using is too long to post here. But I copied and pasted
This article to give it a test and it showed 32 counts of white space, not including the white space in front of or behind of other words even after using trim().
Here's a js.fiddle of the raw data that is being handled by php.
htmlentities and htmlspecialchars also show nothing.
Here's the code counts all the values and puts them into one.
$inhere = array();
$body_hold = array();
foreach($search_body as $value){
$value = trim($value);
if(in_array($value, $inhere) && $value != ""){
$key = array_search($value, $inhere);
$body_hold[$key]['count'] = $body_hold[$key]['count']+1;
}elseif($value != ""){
$inhere[] = $value;
$body_hold[] = array(
'count' => 1,
'word' => $value
);
}
}
rsort($body_hold);
Basic foreach to see values.
foreach($body_hold as $value){
$count = $value['count'];
$word = trim($value['word']);
echo "Count: ".$count;
echo " Word: ".$word;
echo '<br>';
}
Here's a PHP example of what it's returning
Are you sure you put the exact same data you're processing in the js.fiddle? Or did you get it from a subsequent post-processed step?
It's obviously a Wikipedia article. I went to that article on Wikipedia and opened it in Edit mode, and saw that there are s in the raw wikitext. However, those nbsp's don't appear in your js.fiddle data.
TL;DR: Check for in your processing (and convert to spaces, etc.).
This character 160 looks like space but it's not, replacing all of them to the regular spaces (32) and then removing all the double spaces will fix your problem.
$search_body = str_replace(chr(160), chr(32), $search_body);
$search_body = trim(preg_replace('/\s+/', ' ', $search_body));

extract info from another web page

I have this test.php where i have this info :
callername1 : 'Fernando Verdasco1'
callername2 : 'Fernando Verdasco2'
callername3 : 'Fernando Verdasco3'
callername4 : 'Fernando Verdasco4'
callername5 : 'Fernando Verdasco5'
this page automatically changes that name every 10 min
In this another page test1.php
I need a php code that takes only the name of the callername3 and echo'it
Fernando Verdasco3
I've tried this like so test1.php?id=callername3
<?php
$Text=file_get_contents("test.php");
if(isset($_GET["id"])){
$id = $_GET["id"];
parse_str($Text,$data);
echo $data[$id];
} else {
echo "";
}
?>
but no result.
Is there any other option?
If i have "=" instade of ":"
callername1 = 'Fernando Verdasco1'
callername2 = 'Fernando Verdasco2'
callername3 = 'Fernando Verdasco3'
callername4 = 'Fernando Verdasco4'
callername5 = 'Fernando Verdasco5'
And i use This php Code it works
<?php
$Text=file_get_contents("test.php")
;preg_match_all('/callername3=\'([^\']+)\'/',$Text,$Match);
$fid=$Match[1][0];
echo $fid;
?>
i need this to work with ":"
Help?
You should store data in a file with the .php extension, since it's not executable PHP. I looks like you're going for the JSON syntax.
Since you need it to work with ':' I assume, for whatever reason, you can't change the format. Your example with '=' works because of the regexp:
preg_match_all('/callername3=\'([^\']+)\'/',$Text,$Match);
This says, match text like callername3= followed by a ' followed by one or more chars that are not a ' followed by a final '. Everything between the 's is stored in $Match[1][0] (if there were more parts in brackets they be stored in $Match[2][0], etc).
Your example doesn't work since it doesn't account for the spaces before and after the = sign. But we can fix that up and change it to work for : like this:
preg_match('/callername3\s*:\s*\'([^\']+)\'/',$Text,$Match);
echo $Match[1] ."\n";
This displays:
Fernando Verdasco3
And what that regular expression is match text that start callername3 followed by any amount of whitespace (that's the \s*) followed by a :, followed by any amount of whitespace, followed by a name in quotes (that is stored in $Match[1], this is the area of the regular expression enclosed in parenthesis).
I've also used just preg_match because it looks like you only need to match one example.
There is a rather simple approach to tihs:
$fData = file_get_contents("test.php");
$lines = explode("\n", $fData);
foreach($lines as $line) {
$t = explode(":", $line);
echo trim($t[1]); // This will give you the name
}

How do I remove html tags and other characters from a text field

The fields contains the value of : {"93":" Size:</span>XL</span>"}. I want to display only Size: XL. I have tried using the strip_tag function but have been unsuccessful. Are there any suggestions?
Try this,
Its json encoded value.
$text = '{"93":" Size:</span>XL</span>"}';
$ar = json_decode($text);
foreach($ar as $value){
echo strip_tags($value);
}
The output will be
Size:XL
Hope its fixed ..
If your tag was correct, like so:
<span>XL</span> instead of </span>XL</span>,
strip_tags() should work for you.
I verified with the following test...
$text = "<span>XL</span>";
$goodtext = strip_tags($text);
And output the results...
echo htmlentities($text)
echo "<br/>";
echo htmlentities($goodtext);
Yielded...
<span>XL</span>
XL
Your question was a bit unclear, if the field contains all there including the { brackets, then this regex in a replace should help, just replace the characters with an empty string:
/"\:"|[^A-Za-z:]|span/g
If that is not the case and you only have the second string with the spans, you could use this one:
/[^A-Za-z:]|span/g
Be warned though, it also removes spaces and only works in specific cases, eg. does not remove other tags etc.
You could apply a global regular expression match using the function preg_match_all to extract only "Size: XX" from your field.
$field = "your data fields"
$pattern = "/(Size:)<\/span>([a-z]{1,2})<\/span>/i";
preg_match_all($pattern,$field,$result,PREG_SET_ORDER);
foreach( $result as $r ) {
print($r[1]." ".$r[2].PHP_EOL);
}
Will output:
Size: XL
Size: L
...

echo characters only in one line with explode function php

here is what i want to do
i am working with php explode function trying to limit characters it prints after defined condition
{
$result=http://php.net
new line characters i don't want to print
$links =explode("://",$result);
$nows=$links[1];
echo $nows;
}
as you can see the above code will print
php.net
new line characters i don't want to print
but instead i want to stop printing after
php.net
You can replace newline characters with nothing:
$nows = str_replace("\n", "", $links[1]);
$nows = str_replace("\r", "", $nows);
echo $nows;
If you want only what is printed on the first line, try this:
$result = "php.net
and some other text";
$nows = reset(explode("\n", str_replace("\r\n", "\n", $result)));
If the part you're looking after will always be in the first line:
$result="http://php.net
new line characters i don't want to print";
$links = explode("\n",$result);
/*
$links[0] ->http://php.net
$links[1] ->new line characters i don't want to print
*/
$links =explode("://",$links[0]);
$nows=$links[1];
echo $nows;
/*
php.net
*/
Anyway , Consider giving more details about your case in order to offer a better way.
For instance , maybe regex?
Try
$nows = trim( $links[1] );
TRIM() will remove newlines among other things
Manual page
EDIT:
Well now we have the actual situation which you say is :-
$result=http://php.net</br>nameserver:ns1</br>nameserver:ns2.
Try
$t = explode( '</br>', $result );
$t1 = explode ( '://', $t[0] );
echo $t1[1];
Just as a note, if it is you that is creating this string somewhere else </br> is not a valid html tag, it should be <br> or if you are using XHTML it should be <br />.

PHP: Reading first character of exploded string in while loop. Empty characters causing issues

Probably a simple problem here, but I cannot find it.
I am exploding a string that was input and stored from a textarea. I use nl2br() so that I can explode the string by the <br /> tag.
The string explodes properly, but when I try to get the first character of the string in a while loop, it only returns on the first line.
Note: The concept here is greentexting, so if you are familiar with that then you will see what I am trying to do. If you are not, I put a brief description below the code sample.
Code:
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$comment = nl2br($row['comment']);
$sepcomment = explode("<br />", $comment);
$countcomment = count($sepcomment);
$i = 0;
//BEGIN GREENTEXT COLORING LOOP
while($i < $countcomment) {
$fb = $sepcomment[$i];
$z = $fb[0]; // Check to see if first character is >
if ($z == ">") {
$tcolor = "#789922";
}
else {
$tcolor = "#000000";
}
echo '<font color="' . $tcolor . '">' . $sepcomment[$i] . '</font><br>';
$i++;
}
//END GREENTEXT COLORING LOOP
}
Greentext: If the first character of the line is '>' then the color of that entire line becomes green. If not, then the color is black.
Picture:
What I have tried:
strip_tags() - Thinking that possibly the tags were acting as the first characters.
$fb = preg_replace("/(<br\s*\/?>\s*)+/", "", $sepcomment[$i]);
str_replace()
echo $z //Shows the correct character on first line, blank on following lines.
$z = substr($fb, 0, 1);
Here is a test I just did where I returned the first 5 characters of the string.
Any ideas for getting rid of those empty characters?
Try "trim" function
$fb = trim($sepcomment[$i]);
http://php.net/manual/en/function.trim.php
(probably line breaks are the problem, there are \n\r characters after tag)

Categories