I want to use str_replace te replace some values in a variable and get a variable named $username with the value USERNAME. It works fine for one value but not for multiple values.
This works..
$myabsoluteurl=JURI::current();
$replacestring='http://www.website.com/index.php/component/comprofiler/userprofile/';
$usertemp= str_replace($replacestring, '', $myabsoluteurl);
However there are four possibilities how a url can look so i need 4 variables
$replacestring1='http://www.website.com/index.php/component/comprofiler/userprofile/';
$replacestring2='http://www.website.com/index.php/instellingen/userprofile/';
$replacestring3='http://www.website.com/index.php/component/comprofiler/';
$replacestring4='http://www.website.com/index.php/instellingen';
How can get al four possibilities stripped so i can place the remaining value in a variable? The username is always placed behind one of the four urls...
You can declare $replacestringas an array, and then run a for loop within the array.
$replacestring = array('string1', 'string2');
foreach ( $replacestring as $string ) {
// do stuff
};
Related
With the updated code below, my search is working, but only using the last word in the Array. Is there a way to search the MySQL column using all words the user inputted?
Note: All input sanitization and escaping is completed in my code but not shown here.
I have two PHP arrays: $search_exploded (user inputted search terms) and $metaphoneArr (metaphones of keywords in MySQL).
I'm cycling through $search_exploded and $metaphoneArr, and if the Levenshtein is less than 2, then I'm adding the metaphone element to a third array called $levenResultsArr.
In MySQL, I'm joining two tables, and if there's a result in my third array ($levenResultsArr) that matches a row in my metaphone_col, then I want the results printed. Somehow, though, I am not referencing the third array correctly in the MySQL statement.
Any advice? Here is part of my PHP code.
$levenResultsArr = array();
foreach ($search_exploded as $search_each => $searchWord) {
$search_each2 = metaphone($searchWord);
echo $search_each2 . "<br/>";
foreach ($metaphoneArr as $metaword => $val) {
$lev = levenshtein($search_each2, $val);
if ($lev < 2) {
array_push($levenResultsArr, $search_each2);
}
}
}
// And shown below is the MySQL statement
$constructs = "
SELECT vt.idvideolist,
vt.videotitle,
vt.videodescription
FROM videolist_tbl vt
INNER JOIN keyword__video k2v ON (vt.idvideolist = k2v.video_id)
INNER JOIN keywords_tbl k ON (k2v.keyword_id = k.idkeywords_tbl)
WHERE k.metaphone_col = '$search_each2'
";
It's only searching using the last word in the array instead of all words in the array.
You're correct that you aren't referencing your array correctly in your query. You are simply referencing the variable '$search_each2'. You want to check the entire array. The best way to do this would to be to convert the array to a string using implode and using the MySQL IN clause. We need to modify the array first to format it correctly:
foreach($levenResultsArr as &$foo){
$foo = "'".$foo."'"; //add single quotes around each object in the array
}
$levenAsStr = implode(",", $levenResultsArr);
Then simply change your last line to the following:
WHERE k.metaphone_col IN (".$levenAsStr.")";
Did this from memory because I'm not in a testing environment, please let me know if there are any syntax errors. Should work for you!
Without seeing more of the code its a bit difficult to determine what is going on. A couple of thoughts though.
What var is the array containing all search terms?
I noticed you are pushing items into $levenResultsArr. I don't see it being used in the query though.
If it is $search_each_2 you may try using the IN syntax:
WHERE k.metaphone_col IN '$search_each2';
This will only match exact values however. i.e.:
some value does not return if the IN array contains value. The array would have to contain some value
If you need it to match partial searches you may try using LIKE with wildcards: %
WHERE k.metaphone_col LIKE "%searchTerm1%"
OR k.metaphone_col LIKE "%searchTerm2%"
OR k.metaphone_col LIKE "%searchTerm3%"
You could potentially use the implode function to create the sql string from the array: http://php.net/manual/en/function.implode.php
Cannot get my head around why a variable pulled from a db is not working.
I have an array that I am searching using array_search().
Using the function like so:
$band2 = taxBandtoPrice2("$car->tax_band");
echo "(£$band2 Per Year)";
Note, "$car->tax_band" is a query that takes the tax_band value. This part works for a certain.
$band2 is always blank. If i replace "$car->tax_band" with 'c' it works fine.
How should I be doing this where might I be going wrong?
The function itself:
function taxBandtoPrice2($taxband){
$bands = array(
0 => 'a',
1 => 'b',
...
);
$key = array_search($taxband, $bands);
return $key;
}
Looking at the code it should work. You can try following changes:
$band2 = taxBandtoPrice2($car->tax_band);
echo "(£{$band2} Per Year)";
Ensure with var_dump($car->tax_band) and later with var_dump($band2) what values and types are. What can I think off are two reasons:
$car->tax_band is not equal to values in $bands. Even a single
space and lower/uppercase makes difference.
List item $car->tax_band gets
overwritten before passed to function.
Simple fix for me on this one.
I was passing in a C but the values in my array were in lower case...
I changed the value to a lowercase with
strtolower();
I tried many time, but I still don't understand why the output is not a string, anything wrong ? help me check it. The final output should be a uppercase name string
<html>
<p>
<?php
// Create an array and push on the names
// of your closest family and friends
$name = array();
array_push($name,"Mike");
array_push($name,"Jane");
array_push($name,"Jack");
array_push($name,"Nike");
array_push($name,"Ash");
array_push($name,"Chris");
array_push($name,"Zark");
// Sort the list
sort($name);
join(",",$name);
// Randomly select a winner!
$random = count($name,rand(0,7));
// Print the winner's name in ALL CAPS
$winner = strtoupper($random);
print($winner);
?>
</p>
</html>
$random = count($name,rand(0,7));
This line assigns the count of elements in $name. I don't know what else you expected to get back other than a number here.
What you really want:
echo strtoupper($name[array_rand($name)]);
http://php.net/manual/en/function.array-rand.php
Other Notes:
Your call to join() doesn't do anything useful since you're not doing anything with the return value.
Your call to sort is pointless if you're just picking a random entry later.
Pick a plural name for your array names so you know they are arrays. $names instead of $name.
If you know all of the array elements ahead of time, no need for array_push(), just use an array literal: array('Mike', 'Jane', /* etc */)
If you're outputting data into the context of HTML, always use htmlspecialchars() to make sure any reserved characters are escaped properly. This isn't a problem with the code you literally have here, but will be as soon as you want to output < or ".
I seem to have looked everywhere for this.
Here is the code i use to set a variable to a piece of data from a MySQL database
$PartNo=mysql_result($result,$i,"PartNo");
Where
$result = mysql_query("SELECT * FROM PriceList");
$i = 0, is added to by 1 every time my while loop restarts
PartNo is a field name in my MySQL table and also the name of the variable I want to set the data in the database to
PriceList is my database name
I want to loop through all the field names (the array has them) and set variables with the same names to that data. Like this:
$PartNo=mysql_result($result,$i,"PartNo");
$Group=mysql_result($result,$i,"Group");
$OnHand=mysql_result($result,$i,"OnHand");
$QOO=mysql_result($result,$i,"QOO");
$Description=mysql_result($result,$i,"Desc");
$Cost=mysql_result($result,$i,"Cost");
But with a foreach loop so it isn't as much code.
I was thinking something like this, but it won't execute no matter which way I go about it (parse_str, eval, exec, etc.)
$nDatabaseVars=array("PartNo","Group","OnHand","QOO","Desc","Cost");
foreach ($nDatabaseVars as $X) {
$$X=mysql_result($result,$i,'$X');
}
I need "$$X" to evaluate out so on the first iteration, it changes to $PartNo= and then sets $PartNo to whatever data is in the database on the first line. Which is what this part is: mysql_result($result,$i,"PartNo")
If I echo it out instead:
foreach ($nDatabaseVars as $X) {
echo "$$X=mysql_result($result,$i,'$X')";
}
I can get it to say exactly what I need executed ($PartNo=mysql_result($result,$i,"PartNo");) but not actually get the variable set.
You are passing a string containing "$X" to mysql_result, not the name of your column. Remove the single quotes:
$$X=mysql_result($result, $i, $X);
$$X=mysql_result($result,$i,'$X'); // these single quotes around $X avoid your actual string to be used.
$$X=mysql_result($result,$i,"$X");
I have a cookie which I'm trying to split. The cookie is in this format:
key = val1,val2,val3 (where each value is separated by commas)
is there a way for me to split this in a loop so that I can directly access val3?
I've tried using the explode() function with no success.
for ($i = 0; $i < count($_COOKIE); $i++)
{
$ind = key($_COOKIE);
$data = $_COOKIE[$ind];
//I try and slit the cookie here
$cookie_temp = explode(",",$_COOKIE[$ind]);
//Here is where I wanted to display Val3 from the cookie
print $cookie_temp[2];
next($_COOKIE);
}
my code works fine but I then end up with all my Val3 in a large array. For example, my val3's are numbers and they get put in an array. Can I split this even further?
First of all, I'm hoping you know the name of the cookie you're trying to get the value of. Let's call it mycookie in the rest of my answer.
Second, just scrap the whole loop thing and just access $_COOKIE['mycookie'] directly.
Then, you can now call explode(",",$_COOKIE['mycookie']) to get the separate values.
Next, just get index 2 with [2] as you are in your current code.
As a shortcut, if the second one is the only one you need:
list(,,$val) = explode(",",$_COOKIE['mycookie']);
Assuming you are looping because you have multiple comma-separated cookie key/value groups, use a foreach() instead and with list() you can retrieve the third value with a direct assignment.
foreach ($_COOKIE as $key=>$value) {
list($v1, $v2, $v3) = explode("," $value);
echo $v3;
}
If you have only one cookie value to access, there is no need for the loop, and you can directly call explode(",", $_COOKIE['key'])
PHP 5.4 allows array dereferencing, whereby you can directly access the array element off of the explode() call, but this won't work in earlier PHP versions.
echo explode(",", $_COOKIE['key'])[2];