I need to check if URL contains the term: "cidades".
For example:
http://localhost/site/cidades/sp/sorocaba
So, if positive, then I need to create two or three variables with the remaining content without the " / ", in this case:
$var1 = "sp";
$var2 = "sorocaba";
These variables will be cookies values in the beggining of the page, then, some sections will use as wp-query these values to filter.
This should work for you:
Here I check with preg_match() if the search word is in the url $str between two slashes. If yes I get the substr() from the url after the search word and explode() it into an array with a slash as delimiter. Then you can simply loop through the array an create the variables with complex (curly) syntax.
<?php
$str = "http://localhost/site/cidades/sp/sorocaba";
$search = "cidades";
if(preg_match("~/$search/~", $str, $m, PREG_OFFSET_CAPTURE)) {
$arr = explode("/", substr($str, $m[0][1]+strlen($m[0][0])));
foreach($arr as $k => $v)
${"var" . ($k+1)} = $v;
}
echo $var1 . "<br>";
echo $var2;
?>
output:
sp
sorocaba
Here are two functions that will do it for you:
function afterLast($haystack, $needle) {
return substr($haystack, strrpos($haystack, $needle)+strlen($needle));
}
And PHP's native explode.
First call afterLast, passing the /cidades/ string (or just cidades if you don't expect the slashes). Then take the result and explode on / to get your resulting array.
It would look like:
$remaining_string = afterLast('/cidades/', $url);
$items = explode('/', $remaining_string)
Just note that if you do not include the / marks with the afterLast call, your first element in the explode array will be empty.
I think this solution is better, since the resulting array will support any number of values, not just two.
Related
$d5 = preg_grep("/(#[0-9]{1,11})/", $d);
in the code above:
$d is a $_POST method textarea input.
I have a preg_grep to find and capture numbers following an # symbol like this: #1234567890
I want to INSERT the $d5 results to a table in the database, but since the preg_grep should return an array I can't put them in as it is. So I tried to use the following method
$d5string = implode(", ", $d5);
but obviously I couldn't address the $d5 results appropriately.
How can I convert this $d5 results to string so I can INSERT the results to a row under related column?
EDIT/UPDATE:
I wrote the below function and realized that I was giving a string to the preg_grep which takes an array. So my question was not logical. I'd like to update my question: How to capture and put regex results to database?
function activeMention($string) {
$find = '/#([0-9]{1,11})/';
return preg_grep($find, $string);
}
I replaced preg_grep() with preg_match_all() in the function. Now the error is gone and var_dump shows int(0)
on variable $d5 = activeMention($string); I put a $_POST['textarea_name'] value as $string
NOW:
The function looks like this:
function activeMention($string) {
$find = '/#([0-9]{1,11})/';
return preg_match_all($find, $string, $matches);
implode(', ', $matches);
}
When I try to insert the variable below to the database I get only the count of captured strings:
$d5 = activeMention($_POST['textarea_name']);
What I actually needed was the array values in 1 string like "#123123, #1234567, #12345"
To get more than one match from a regular expression, you could use preg_match_all like this:
// Define string
$d = 'Here goes one #1234567890 and a #987654321';
// Run regular expression and put matches into $d5 (array with arrays)
$found = preg_match_all("/(#[0-9]{1,11})/", $d, $d5);
// Iterate result
foreach ($d5[0] as $number) {
echo $number, PHP_EOL; // ... or insert into database
}
Output:
#1234567890
#987654321
Here's finally how I did it:
I got rid of the function and used preg_match_all like this:
preg_match_all('/#([0-9]{1,11})/', $_POST['textarea_name'], $out);
$d5s = implode(', ', $out[0]);
and added $d5s to the VALUES in the query to insert into database.
In a comma delimited string, in php, as such: "1,2,3,4,4,4,5" is it possible to say:
if(!/*4 is in string bla*/){
// add it via the .=
}else{
// do something
}
In arrays you can do in_array(); but this isn't a set of arrays and I don't want to have to convert it to an array ....
Try exploding it into an array before searching:
$str = "1,2,3,4,4,4,5";
$exploded = explode(",", $str);
if(in_array($number, $exploded)){
echo 'In array!';
}
You can also replace numbers and modify the array before "sticking it back together" with implode:
$strAgain = implode(",", $exploded);
You could do this with regex:
$re = '/(^|,)' + preg_quote($your_number) + '(,|$)/';
if(preg_match($re, $your_string)) {
// ...
}
But that's not exactly the clearest of code; someone else (or even yourself, months later) who had to maintain the code would probably not appreciate having something that's hard to follow. Having it actually be an array would be clearer and more maintainable:
$values = explode(',', $your_string);
if(in_array((str)$number, $values)) {
// ...
}
If you need to turn the array into a string again, you can always use implode():
$new_string = implode(',', $values);
i got a piece of code that so far returns me data like this when i use print $result;
ssl_card_number=41**********1111
ssl_exp_date=0213
ssl_amount=132.86
ssl_salestax=0.00
ssl_invoice_number=5351353519500
ssl_result=0
ssl_result_message=APPROVED
ssl_txn_id=00000000-0000-0000-0000-00000000000
ssl_approval_code=123456
ssl_cvv2_response=P
ssl_avs_response=X
ssl_account_balance=0.00
ssl_txn_time=11/21/2012 12:38:20 PM
thats from view page source.
and the page itself shows it as :
ssl_card_number=41**********1111 ssl_exp_date=0213 ssl_amount=132.86 ssl_salestax=0.00 ssl_invoice_number=8601353519473 ssl_result=0 ssl_result_message=APPROVED ssl_txn_id=00000000-0000-0000-0000-00000000000 ssl_approval_code=123456 ssl_cvv2_response=P ssl_avs_response=X ssl_account_balance=0.00 ssl_txn_time=11/21/2012 12:37:54 PM
i need to be able to handle each of the "keys" in a better way and dont know how to explode them maybe ?
One possible approach:
parse_str(preg_replace('#\s+(?=\w+=)#', '&', $result), $array);
var_dump($array);
Explanation: preg_replace will turn all the whitespace before the param names into '&' symbol - making this string similar to the regular GET request url. Then parse_str (the function created specifically for parsing such urls) will, well, parse this string (sent as the first param), making an associative array of it.
In fact, you don't even have to use preg_replace here, if each param=value string begins from a new line; str_replace("\n", '&') should do the trick.
An alternative approach:
$pairs = preg_split('#\s+(?=\w+=)#', $x);
foreach ($pairs as $pair) {
list ($key, $value) = explode('=', $pair, 2);
$array[$key] = $value;
}
Here you first create an array of 'key-value pair' strings, then split each element by =: the first part would be the key, the second - the value.
You can use the regular expression reported by #raina77ow or you could use explodes (riskier):
<?php
$tmps = explode("\n",$result); //this gives you each line separate
foreach($tmps as $tmp){
list($key,$value) = explode('=',$tmp,2);
echo $key.' has value '.$value."\n";
//you can even create vars with the "key" if you are sure that they key is a "clean" string:
$$key=$value;
//or put everything into an array - similar to the regexp
$result_array[$key] = $value;
}
?>
How can I prepend a string, say 'a' stored in the variable $x to each line of a multi-line string variable using PHP?
Can also use:
echo preg_replace('/^/m', $prefix, $string);
The / are delimiters. The ^ matches the beginning of a string. the m makes it multiline.
demo
There are many ways to achieve this.
One would be:
$multi_line_var = $x.str_replace("\n", "\n".$x, $multi_line_var);
Another would be:
$multi_line_var = explode("\n", $multi_line_var);
foreach($multi_line_var AS &$single_line_var) {
$single_line_var = $x.$single_line_var;
}
$multi_line_var = implode("\n", $multi_line_var);
Or as a deceitfully simple onliner:
$multi_line_var = $x.implode("\n".$x, explode("\n", $multi_line_var));
The second one is dreadfully wasteful compared to the first. It allocates memory for an array of strings. It runs over each array item and modifies it. And the glues the pieces back together.
But it can be useful if one concatenation is not the only alteration you're doing to those lines of text.
Because of your each line requirement, I would first split the string to an array using explode, then loop through the array and add text to the beginning of each line, and then turn the array back to a string using implode. As long as the number of lines is not very big, this can be a suitable solution.
Code sample:
$arr = explode("\n", $x);
foreach ($arr as $key => $value) {
$arr[$key] = 'a' . $arr[$key];
}
$x = implode("\n", $arr);
Example at: http://codepad.org/0WpJ41LE
Can someone suggest a simple function that will parse a string into two parts, based on everything before and after the comma? I want to split up a latitude longitude pair so that I have two variables instead of one.
I need to turn this:
-79.5310706,43.6918950
into this:
-79.531070
43.6918950
$parts = explode(",", "-79.5310706,43.6918950");
echo $parts[0];
// -79.5310706
echo $parts[1];
// 43.69189506
Or if you need it to stay as a space-separated string, just str_replace() the comma to a space!
echo str_replace(",", " ", "-79.5310706,43.6918950");
// -79.531070 43.6918950