Hi (sorry for my english xD),
I'm taking data of my DB in MySql, this data (pair of players in format 'Player 1 - Player 2'). I cut this with explode function by character - therefore I get 'Player 1 ' and ' Player 2' string. I try delete white spaces at the beginning and the end with trim function, but this don't work. I suspect that this trouble is similar to other with the - character, the normal - of my keyboard don't split the string with explode function, I had to go to PHPMyAdmin and copy the - character of the one existing string and paste this in the second explode function parameter, after this, explode function work.
I try the same of the - character (Login in PHPMyAdmin copy one whitespace and paste this as second parameter of trim function but this time don't work :( ).
Also try with str_replace function (no matter what the gaps are eliminated) and don't work, also try with preg_replace function etc... nothing has work because apparently the white space saved in DB isn't the same of my keyboard, I suspect that the problem is related with charset's or collations but I don't have idea what I should do, because the table, link, charset of PHP and other thing are in UTF-8 and utf8-spanish-ci collation and charset.
Aclaration: The input of the data is made by xdom (PHP) from other site not controlled for me.
<tbody>
<?php while ($partidos = mysqli_fetch_array($sql)) { ?>
<tr>
<td class="center"><?php echo $partidos['fecha']; ?></td>
<td><?php $participante = explode("₋", $partidos['jugadores']);
$participante1 = trim($participante[0]);
$participante2 = trim($participante[1]);
echo trim($participante1) . "<br>vs<br>" . trim($participante2);
?></td>
<td><?php if ($partidos['estado'] == 0) { ?> En Curso<?php } elseif ($partidos['estado'] == 1) {
if ($partidos['alerta'] == 0) { ?> Terminado<?php } else { ?>Terminado - Error <i
class="fa fa-exclamation-triangle"></i><?php }
} ?></td>
<td><?php if ($partidos['alerta_medica'] == 1) { ?> Si <i class="fa fa-2 fa-medkit"
style="color:#C00;"></i><?php } else { ?> No<?php } ?>
</td>
<?php if ($_SESSION['tipo'] == 1 || $_SESSION['tipo'] == 2) { ?>
<td class="center">
</td>
<?php } ?>
</tr>
<?php } ?>
</tbody>
I found the problem thanks to #Rick James, watching the hexadecimal response of the database i noticed that two spaces are x20, but one is xC2 xA0. Reading in other post of stackoverflow, i found that xC2 xA0 is a Non-break space, but this is not recognized for the trim function. The solution was specify this as second parameter of the function:
$participante1 = trim($participante[0],"\x20,\xC2,\xA0");
$participante2 = trim($participante[1],"\x20,\xC2,\xA0");
Now the whitespaces are removed correctly :3
Thanks to all for give your help to solve this :)
Since you have 3 blanks on either side of the special character split the strings by 3 spaces.
like this:
<?php
foreach( $strings as $string) {
$players = explode(" ",$string);
print "Player 1: " . $players[0] . PHP_EOL;
print "Player 2: " . $players[2] . PHP_EOL;
}
Related
I am looking for some guidance on checking for a string that is returning string(1) " ".
I am rendering a button in a WordPress template file. I first get the post meta, which is added via an API update. I then parse it so as to add the ID to an external booking url.
I need to test to ensure a value is returned of course. However, if I use !empty , this isn't working because even if the field has no value entered, it is still returning string(1) " " from the database.
I could test for strlen, but this doesn't seem very elegant. What would be the best way to test for this?
Many thanks
$s_apply_url0 = get_post_meta( $event_id, '_MyBookingURL', true);
parse_str($s_apply_url0, $output);
$s_apply_url1 = 'https://mybookings.com/event/' . $output ['id'];
if (!empty($s_apply_url0): ?>
<aside id="applybutton-2" class=" grop-side-widget widget_applybutton">
<a href="<?= $s_apply_url1; ?>" class="btn course-apply">
<?= $s_apply_text1 ?>
</a>
</aside>
<?php endif; ?> ```
If I've understood this question correctly, you want to be able to test whether the string is empty or contains more than one space characters
You could first use the trim function of PHP in order to 'trim' the string of whitespace (or, arbitrarily any other characters you wish to determine as 'blank').
<?php
if (empty(trim($myString)) {
// the string is empty, or contains only whitespace
}
If you wish to ONLY test for a single ' ' character, then you could just add that into your conditions, eg:
<?php
if (empty($myString) || $myString === ' ') {
// $myString is empty or only contains a single space character
}
I'm having trouble figuring out how to implement a search on an SQL db when parts with non-alphanumerical characters are searched.
The search works great except when there is a character such as a hyphen, or parentheses in the part number being searched. (Some part numbers have forward slashes, but those are returned properly when queried.)
For example: A search for 1492-PDL3111 returns 0 results.
(Partial string searches work well, so if I search for 1492 I will get the 1492-PDL3111 part number returned along with 1492-PDL31124, 1492-PDL3141, 1492-PDL3161, which is great, but if I include the hyphen, I'm back to 0 results. I also get correct results when I do a partial string search from the middle or end of a string. The only failure is when I do a search for a part number which has non-numerical characters.
I'm pasting the code below with the hope someone here can assist. I've searched and searched for a solution to no avail.
Thanks in advance!
Thymallus
<?php
$searchcross=$_GET[ 'crossref'];
$remove=array( " ", "-");
$searchcross=str_replace($remove, "", $searchcross);
if ($searchcross !="" ){
$query=$handler->prepare("SELECT * FROM php_cross_reference WHERE competitor_part_no LIKE :part_no ORDER BY competitor_part_no;");
$query->bindValue(':part_no', '%' . $searchcross . '%');
$query->execute();
if ($query->rowCount()){ ?>
<!--If statement, only make this if there are results?-->
<div class="table-section">
<table class="search-table search-table-alt">
<caption>
<?php echo 'Search results for "'. $searchcross . '"' ?>
</caption>
<tr>
<th>Competitor Part Number</th>
<th>Competitor</th>
<th>Our Part Number</th>
</tr>
<!--This is where the PHP loop should begin-->
<?php
while ($r=$query->fetch(PDO::FETCH_ASSOC)){
?>
<tr>
<td>
<?php
echo '<strong>',$r[ 'competitor_part_no'], '</strong>'
?>
</td>
<td>
<?php
if ($r[ 'competitor_name']){
echo $r[ 'competitor_name'];
} else {
echo 'N/A';
}
?>
</td>
<td>
<?php
if ($r[ 'product_documentation']){
echo '<strong>',$r[ 'our_part_no'], '</strong>';
} else {
echo '<strong>',$r[ 'our_part_no'], '</strong>';
} ;?>
</td>
<?php
}
//PHP loop end
?>
</table>
</div>
<!-- PHP if statement end?-->
<?php
} else {
echo '<h3 class="module">Your search returned '.$query->rowCount().' results.</h3>';
}
} else {
echo '<h3 class="module">please enter a search</h3>';
}
?>
You're removing hyphens and spaces from the search string when you do:
$searchcross=str_replace($remove, "", $searchcross);
If you want to ignore these characters when searching, you also need to remove them from the strings in the table. So the condition in the query should be:
WHERE REPLACE(REPLACE(competitor_part_no, '-', ''), ' ', '') LIKE :part_no
Thanks for the input. The spaces and hyphens were actually being removed from this array:
$remove=array( " ", "-");
That's not what was desired and once I looked at their code again, I saw the issue.
I removed that line of code and it works perfectly.
I have a number of table rows, which I choose according to the number of items that I plan to extract from my database.
I don't render the rows automatically, because in some of them I want to have the freedom to include some static elements that do not have a certain uniform (see ABC, XYZ in code for example).
For each item (person) I also manually set in the PHP file itself, some other relevant values for his particular row, such as $company[i]
PHP:
<?php
// Choose Relevant people, and turn them into an array
$item_array = array(
'Mike',
'Bill',
'Joe'
);
//implode items, turn into string
$item_implode = join("','", $item_array);
//declare an overall array for result
$person = array();
$personList = array();
$result = $mysqli->query("SELECT available from people_table where available IN ('$item_implode') ORDER BY FIELD (available, '$item_implode');");
if ($result->num_rows > 0) {
$x = 1;
// output data of each row
while($row = $result->fetch_assoc()) {
$person[$x]["available"] = $row['available'];
$x = $x + 1;
}
} else {
echo "0 results";
}
// Manually Set Values:
$hide1=false;
$comment1="hello";
$company1="apple";
$hide2=false;
$comment2="something";
$company2="microsoft";
// And so on...
?>
Since I add another code block for each row, I have to replace in each block the index number, according to the order of the row in the HTML code, which means that in each block, I should CTRL-F the number, and replace it with the following number, which doesn't feel very efficient:
HTML:
// First Row
<?php if ($person[1]["available"]=="yes") { ?>
<tr<?= !$hide1 ? "" : " class=\"hidden\""; ?>>
<td>ABC</td>
<td><?= !$comment1 ? "" : "<div class=\"cell\">" . $comment1 . "</div>"; ?></td>
<td><?= some_function( $company1 ) ?></td>
</tr>
<?php } else { } ?>
// Second Row
<?php if ($person[2]["available"]=="yes") { ?>
<tr<?= !$hide2 ? "" : " class=\"hidden\""; ?>>
<td>XYZ</td>
<td><?= !$comment2 ? "" : "<div class=\"cell\">" . $comment2 . "</div>"; ?></td>
<td><?= some_function( $company2 ) ?></td>
</tr>
<?php } else { } ?>
// and so on
Is there any way to get the indexing number which appears in the end of each variable, to be generated automatically according to the row number in the HTML?
Edit:
Thanks to Andrew Cheong's answer I made an advancement:
I switch all variables that end with a fixed number, into [i] form.
I added a while loop (one line after code start, and another line before code end) to each Table Row, which allows me to indicate index number just once:
So it works fine but I think it's not perfect yet, how else shall I modify it?
New Code:
// First Row
<?php if ($person[1]["available"]=="yes") { ?>
<?php $i = 1; while ($i > 0) { ?> /// New Line #1
<tr<?= !$hide[$i] ? "" : " class=\"hidden\""; ?>>
<td>ABC</td>
<td><?= !$comment[$i] ? "" : "<div class=\"cell\">" . $comment[$i] . "</div>"; ?></td>
<td><?= some_function( $company[$i] ) ?></td>
</tr>
<?php break; } ?> /// New Line #2
<?php } else { } ?>
// Second Row
<?php if ($person[2]["available"]=="yes") { ?>
<?php $i = 2; while ($i > 0) { ?> /// New Line #1
<tr<?= !$hide[$i] ? "" : " class=\"hidden\""; ?>>
<td>XYZ</td>
<td><?= !$comment[$i] ? "" : "<div class=\"cell\">" . $comment[$i] . "</div>"; ?></td>
<td><?= some_function( $company[$i] ) ?></td>
</tr>
<?php break; } ?> /// New Line #2
<?php } else { } ?>
// and so on
You could use actual arrays, still—
// Manually Set Values:
$hide[1]=false;
$comment[1]="hello";
$company[1]="apple";
$hide[2]=false;
$comment[2]="something";
$company[2]="microsoft";
and where they don't apply, simply don't set them, e.g.
$comment[3]="only a comment";
and in your HTML,
<?php
if ($person[1]["available"]=="yes") { ?>
<tr<?= !isset($hide[$i]) || !$hide[$i] ? "" : " class=\"hidden\""; ?>>
<td>ABC</td>
<td><?= !isset($comment[$i]) || !$comment[$i] ? "" : "<div class=\"cell\">" . $comment[$i] . "</div>"; ?></td>
<td><?= if (isset($company[$i])) { some_function( $company[$i] ); } ?></td>
</tr>
<?php } else { } ?>
I didn't do all the work for you, but you can see I've modified it so you can now place the thing in a loop indexing over $i.
If you don't know how many $i there will be, then use a while loop, and get creative, e.g. break when isset($hide[$i]) && isset($comment[$i]) && isset($company[$i]) == false.
If you want to hide the comment column altogether, then pull the isset outside the <td> so that you don't even created a <td> in that case.
The way I've wrapped some_function... in an if( ... ) probably won't work because you're using the short-echo form <?= => but I'll let you figure that out.
Re: New Code / Comments
Let me take your new code and modify it a little. I'm going to fix the formatting too so that indentations match up, too:
<?php
$i = 1;
while ($i > 0) {
if ($person[$i]["available"]=="yes") {
?>
<!--
Only add the hidden class if $hide[$i] has been set by someone,
i.e. you, manually, AND it has been set to true.
-->
<tr<?= isset($hide[$i]) && $hide[$i] ? " class=\"hidden\"" : ""; ?>>
<td>ABC</td>
<!--
Same as above, only add the comment div if it has been set, but
instead of what you're doing, I'm going to do what I think you
meant to do: only if there's a non-empty string for a comment.
-->
<td><?= isset($comment[$i]) && $comment[$i] != "" ? "<div class=\"cell\">" . $comment[$i] . "</div>" : ""; ?></td>
<!--
Same thing yet again: only proceed if $company[i] is set and not
an empty string.
-->
<td><?= isset($company[$i]) && $company[$i] != "" ? some_function( $company[$i] ) : "" ?></td>
</tr>
<?php
} // The `else` case is not required.
$i++;
if (!isset($hide[$i]) &&
!isset($comment[$i]) &&
!isset($company[$i]))
{
// Now, this entire thing can be put in a form inside the
// `while`'s condition so that there is no need for this `if`
// statement nor the `break`, but I'm doing it this way to
// make it clearer to you what's going on.
break;
}
}
?>
That's it. No other loops, no other blocks. Now let me answer your questions in your comment:
Of course, no, I didn't mean to use a while per row. That'd be silly and save you no work. I meant the above, where you need only one row.
In my "don't set" example I meant to show that $hide[3] and $company[3] were not set; only $comment[3].
As I'm sure some have tried to tell you, your problem wasn't that you just needed to convert numbers to variables. You actually picked the wrong approach, and unfortunately, stubbornly held onto that approach. I know what it's like to feel like, "Yes, I know! I know! But I have a special case! And in my special case, I need it to be this way!" But seasoned programmers know what kinds of special cases merit certain techniques, and it was obvious that your special case had nothing to do with what's called "reflection" or "variable variables," which you were trying to use. What you were missing were some simple isset()s (and there are probably 10 other ways to do this too, without reflection). isset() checks if, well, you've set the variable, manually, non-manually, whatever. That means you can now create a loop for each <tr> and use isset() on each row's respective variable to see whether you want to do anything with it. If you copy-paste this code to create a new, custom, one-off page, where $hide and $comment and $company are no longer relevant, then guess what: Nothing breaks, because the isset()s will just ignore them. I hope that makes things clearer, but if it doesn't, no worries, as you continue to program, you'll get accustomed to various patterns, and the knowledge will come automatically.
I've got a table which outputs two mySQL records, one original and one which has been edited and flagged for approval/disapproval by the admin. I want to change the column color to highlight rows which have been edited.
The color highlight on changed rows works for all rows except "SalaryFrom" and "Email", for some reason they are always highlighted as different even when the values appear to be completely identical.
Is there any function in PHP which highlights the difference between two strings so I can figure out where the difference is?
Here's my code for one row:
<tr>
<?php
if (htmlval($cand['salaryfrom'])!==htmlval($flaggedcand['salaryfrom']))
{
$tcolor="#000000";
}
else
{
$tcolor="#D3D5E8";
}
?>
<td bgcolor=<?php echo $tcolor ;?>><b>Salary from</b></td>
<td><?php htmlout($flaggedcand['salaryfrom']." "); ?></td>
</tr>
function htmlval($text)
{
return html_entity_decode($text, ENT_QUOTES);
}
Use this
<?php
if ( $cand['salaryfrom'] != $flaggedcand['salaryfrom'] ) $tcolor ="#000000";
else $tcolor="#D3D5E8";
?>
<td style="background: <?php echo $tcolor; ?>;"><b>Salary from</b></td>
<td><?php echo $flaggedcand['salaryfrom'] ." "; ?></td>
There are several reasons why your strings may look the same but they aren't for real. Example: Maybe you need to trim heading and trailing space like this :
function htmlval($text)
{
return trim(html_entity_decode($text, ENT_QUOTES));
}
There are a couple of classes, lib, or self-made function to highlight two strings differences (not in core php) but in your case it might be just enought to output explicitly string 1 and then string 2 so that you can spot the differences by yourself like this :
<tr>
<?php
if (htmlval($cand['salaryfrom'])!==htmlval($flaggedcand['salaryfrom']))
{
$tcolor="#000000";
ob_start();
var_dump(htmlval($cand['salaryfrom']));
echo " is not equal to ";
var_dump(htmlval($flaggedcand['salaryfrom']));
$out = ob_get_clean();
}
else
{
$tcolor="#D3D5E8";
$out = $flaggedcand['salaryfrom'];
}
?>
<td bgcolor=<?php echo $tcolor ;?>><b>Salary from</b></td>
<td><?php htmlout($out." "); ?></td>
</tr>
Hello I am using the following code to get result from the database , in the second dump te results is okay, in the first one there is a problem, because If file is uploaded with space in the name the result is cut after the space:
<?php echo "".$row['pdf']."" ?>
first $row is = 124564
second $row is = 124564 SPRASHORT.pdf
how to fix the first result to be like the second one ?
If you have a space you should encode before linking
<?php echo '' . $row['pdf'] . '' ?>
href should be inside quotes
<?php echo "<a href='pdf/".$row['pdf']."'>".$row['pdf']."</a>" ?>
OR
<?php echo "".$row['pdf']."" ?>