I am using AJAX to retrieve the ID of a certain HTML element. The HTML ID is constructed like "sqlitem_1", "sqlitem_2", "sqlitem_3" etc. and each number corresponds to a record in the database.
I tried preg_replace('/\D/', '', $item);where $item is the string I need to cut, but this didn't do the trick.
Please note that preg_replace doesn't change the argument but rather returns the new value. You might wanna check the preg_replace manual.
So what you need to do is assign the returned value
$item = preg_replace('/\D/', '', $item);
instead.
This could be done either server side (PHP) or if you wanted to preserve the variable name you could use the JavaScript Split function.
JS Split Function (Client Side)
var myVar = "sqlitem_1";
var tmp = str.split("_");
and then access each element using tmp[0] etc
https://www.w3schools.com/jsref/jsref_split.asp
OR
PHP (Server Side)
$ITEMTMP=explode("_", $item);
$itemnumber=$ITEMTMP[1];
http://php.net/manual/en/function.explode.php
Related
How do I get the path info (php) when the path is of the form: www.example.com/post/* (* being a variable number that matches the post id) and compare it to www.example.com/post to make it TRUE.
In other words, if pathinfo is www.example.com/post/1068 (or 1069, or 1070, or whatever the id number) then the statements that follow are executed. If not, then they are skipped.
The snippet is destined to a template file. If this requires a pre-process function, please say so. Thank you.
I am new at this so please do not send me to some other post that reads like Chinese! :)
Thank you.
You could explode and filter for empty values and then use the last occurrence, something rough like this:
$url = "www.example.com/post/1068";
$id = array_pop(array_filter(explode('/', $url)));
$validIds = array("1068", "1069", "1070");
if (in_array($id, $validIds)) {
//do something;
}
explode will separate your string in an array using "/" as a separator (in this case)
array_filter will filter empty values in order to make sure that the last value will be your id
array_pop will retreive the last value of the given array
in_array will compare a value with an array and check if the value is within the given array and return true/false depending whether it is or not inside the array.
I have a 15,000 row PHP array. I need to iterate through each row to generate a 15,000 row Javascript array. Each row of the PHP array has a 5% chance of containing one or more HTML special characters like ó that I need to replace with the equivalent javascript hex. There are about 50 HTML special characters I have to look out for and replace, so I'd use str_replace(array_of_HTML_targets, array_of_hex_replacements, haystack). Is it more efficient to:
Go through each line of the PHP array, search for an ampersand, and if one exists do the search and replace (considering this will apply for only 5% of the rows)
Execute the search and replace on the entire array
Concatenate the array into one giant string and execute the search and replace on the giant string
Other idea? Please specify
Btw, reason for 15,000 PHP array is this is a data visualization app.
Since you already need to dump your PHP data into a string (probably JSON), you might as well work on the final string, like so:
$json = json_encode($your_php_array);
$unhtmlref = preg_replace_callback("/&#(x[0-9a-f]+|\d+);/",function($m) {
if( $m[1][0] == "x") $m[1] = substr($m[1],1);
else $m[1] = dechex($m[1]);
return sprintf("\\u%04s",$m[1]);
},$json);
This is safe, because HTML character codes don't have any special meaning in a JSON string.
That said, I have a function in my JavaScript "utility belt" that does something similar:
function unHTMLref(str) {
// take a string and return it, with all HTML character codes parsed
var div = document.createElement('div');
div.innerHTML = str.replace(/</g,"<");
return div.firstChild.nodeValue;
}
So basically you can either parse before, or after. Personally, I'd prefer "after" because it shifts some of the "grunt" work to the browser, allowing the server to do more important things.
what I need to do is to parse a string similar to this:
{a}3{/a}*{b}4{/b}
or this
{a}3{/a}/{b}2{/b}*100
I need to substitute in that string those values within the tags with real values from the database, the first example:
SELECT value FROM table WHERE id = 3;
SELECT value FROM table WHERE id = 4;
This function:
preg_replace_callback('/(?>{([^}]+)})(.*)?{\/\1}/sim', 'find_tags_callback', $string);
Actually returns the ids contained in the string, the problem is that I'm stuck there. In pseudo code I would need to:
Extract the first id from the string.
Run my query.
Substitute that id with the correct value.
[Do the same for all tags]
Finish having back the initial string with the correct value inside.
The first might be
10*3
the second
40/90*100
Any idea how to do this, I'm completely stuck.
Thanks
Do a database query to get all the values, and put them into an array keyed off the IDs. In the code below, I assume the array is named $tags.
$new_string = preg_replace_callback('/\{([^}]+)\}(.+?)\{/\1\}/sim',
function ($match) use ($tags) {
return $tags[$match[2]];
}, $string);
The use ($tags) declaration allows the function to reference the external variable $tags.
Basically, I have working solution for this, but I'm wondering if it could (should?) be done better in some other way.
I have table I'm creating in PHP with values from MYSQL. Each item in table has multiple values. In each line there is single link and clicking on this link fires up jQuery function. In each link there is also VALUE attribute with values from multiple MYSQL fields and joined with &&:
PHP code is:
foreach ($this->_data as $l)
{
?>
...
<td>Link</td>
...
<?php
}
And jQuery function to fire up when clickin' on link is:
$(".clickMe").click(function() {
myData = $(this).attr('value').split('&&');
});
Script splits string in VALUE attribute on && and creates an array myData with values:
myData[0] => value passed from $l->_data1 in PHP
myData[1] => value passed from $l->_data2 in PHP
Is this the right way to do it?
It's fine, as long as you'll never have && in your data. You could use json_encode() in PHP and then decode this into an array in JavaScript. That would be a more standard solution.
I would recommend against using && which looks like a boolean AND. Instead I would probably use something like a pipe to separate them val1|val2.
I think you're better off passing the whole joined string in to PHP and splitting it out there. It saves you work on both ends having to put the two resultant values into the proper post or get variables to send to PHP.
Then on the PHP side, it's a little easier to validate the one value's format before splitting it, as you can use a single regex like:
// Validate both values at once: 1 or more digits, a pipe, and one or more digits
if (preg_match('/^(\d+)\|(\d+)$/', $_POST['jqueryinput'])) {
// explode() and use in PHP...
list($val1, $val2) = explode("|", $_POST['jqueryinput']);
}
I need to extract a variable's value from a string, which happens to be a URL. The string/url is loaded as part of a separate php query, not the url in the browser.
The url's will look like:
index.php?option=com_content&view=article&catid=334:golfeq&id=2773:xcelsiors&Itemid=44
How can I always find & capture the value of the id which in this example is 2773?
I read several examples already, but what I've tried captures the id value of the current page which is being viewed in the browser, and not the URL string.
Thanks
You are looking for a combination or parse_url (which will isolate the query string for you) and parse_str (which will parse the variables and put them into an array).
For example:
$url = 'index.php?option=com_content&view=article&catid=334:golfeq&id=2773:xcelsiors&Itemid=44';
// This parses the url for the query string, and parses the vars from that
// into the array $vars (which is created on the spot).
parse_str(parse_url($url, PHP_URL_QUERY), $vars);
print_r($vars); // see what's in there
// Parse the value "2773:xcelsiors" to isolate the number
$id = reset(explode(':', $vars['id']));
// This will also work:
$id = intval($vars['id']);
echo "The id is $id\n";
See it in action.
You can use parse_str
You can use parse_url to parse URLs!
But you can use, to extract directly the numbers of ID variable:
$url = 'index.php?option=com_content&view=article&catid=334:golfeq&id=2773:xcelsiors&Itemid=44';
$id = preg_replace("/^.*[&?]id=([0-9]+).*$/",'$1',$url);
echo $id;