I am stuck for several hours with the following problem. I got my own cms where i use a shortcode [plugin-pluginname] to activate a plugin. Now i want to assign a group within that shortcode which is later used in the include once file as variable for a query to select that certain id.
On the moment, I got the following code:
$regex = '~\[plugin-([^]]+)]~';
$content_one = htmlspecialchars_decode($page['content_one']);
$parts = preg_split($regex, $content_one, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach($parts as $k => $v){
if($k & 1)
include_once('plugins/'.$v.'/'.$v.'.php');
else
echo htmlspecialchars_decode($v);
}
This checks where there is [plugin-testplugin](testplugin as an example) and includes that certain file. Now i want to write something like this [plugin-testplugin 2]where not only the above code still works of course, but also that the number is stored in a variable where is can use the query SELECT * FROM 'database' WHERE 'group' = "'.$var_from_shortcode.'"
Any help and answers to approach and solve this problem are welcome!
Could you use this regex then save group 1 value in a variable?
\[plugin-[A-Za-z ]*(\d+)?\]
Or use this regex to find [plugin-testplugin 2] then use \d* to find the number in it?
Related
I am trying to learn PHP while I write a basic application. I want a process whereby old words get put into an array $oldWords = array(); so all $words, that have been used get inserted using array_push(oldWords, $words).
Every time the code is executed, I want a process that finds a new word from $wordList = array(...). However, I don't want to select any words that have already been used or are in $oldWords.
Right now I'm thinking about how I would go about this. I've been considering finding a new word via $wordChooser = rand (1, $totalWords); I've been thinking of using an if/else statement, but the problem is if array_search($word, $doneWords) finds a word, then I would need to renew the word and check it again.
This process seems extremely inefficient, and I'm considering a loop function but, which one, and what would be a good way to solve the issue?
Thanks
I'm a bit confused, PHP dies at the end of the execution of the script. However you are generating this array, could you also not at the same time generate what words haven't been used from word list? (The array_diff from all words to used words).
Or else, if there's another reason I'm missing, why can't you just use a loop and quickly find the first word in $wordList that's not in $oldWord in O(n)?
function generate_new_word() {
foreach ($wordList as $word) {
if (in_array($word, $oldWords)) {
return $word; //Word hasn't been used
}
}
return null; //All words have been used
}
Or, just do an array difference (less efficient though, since best case is it has to go through the entire array, while for the above it only has to go to the first word)
EDIT: For random
$newWordArray = array_diff($allWords, $oldWords); //List of all words in allWords that are not in oldWords
$randomNewWord = array_rand($newWordArray, 1);//Will get a new word, if there are any
Or unless you're interested in making your own datatype, the best case for this could possibly be in O(log(n))
I am trying to iterate through the rows in a phpbb table called phpbb_posts and extract each entry in phpbb's "post_subject" column and compare its value with a predefined string in Wordpress PHP file but I am having some issues - the expressions don't evaluate to true.
My phpBB's tables are installed in WP's database so I have full access to the values.
See the code below to demonstrate the issue I am having.
function matchPhpBBTopic()
{
global $wpdb;
$wp_post_title_string = get_the_title();
$result = $wpdb->get_results("SELECT * FROM phpbb_posts");
foreach($result as $row)
{
$phpbb_post_title_array = array($row->post_subject);
$phpbb_post_title_string = implode("", $phpbb_post_title_array);
// One of the values in $row->post_subject contains
// the value in $wp_post_title_string
if (strcmp($wp_post_title_string, $phpbb_post_title_string) == 0)
{
// This line never runs but the $wp_post_title_string value
// is there, in the table, I've printed it and it's there
echo 'We found a match!<br>';
}
}
}
Any assistance would be appreciated.
So in other words, I have a topic posted in WP and I have exactly the same topic posted in phpBB and I want to iterate through the phpBB's table and when I find the topic, I want to run some code. I don't understand why the "if" expression does not run.
Couldn't you just do:
if ($wp_post_title_string == $phpbb_post_title_string) {}
I don't think strcmp() is appropriate. It converts the string to encoding numbers.
http://us1.php.net/strcmp
Also check for lower and upper case, spaces, and different encodings.
Do strtolower() and trim() first and see what you get.
Also looks like you're imploding subject and title, so don't think they'll match.
I am trying to work out a script to log IPs from poll votes on a message board, that will only be fired off if a vote is cast in one of our polls. Edit: I'm doing this via a web beacon, because I don't have access to the poll's programming. /edit
When the script fires off, it needs to know which poll is being voted in, since there are often multiple polls that are open at the same time, and log the IP of voters in a flat file that is dedicated to that poll.
First, I grab the referring URL, which is formatted like this:
http://subdomain.sample.com/t12345,action=vote
If 'vote' is found in the referring URL, the next thing I want to do is grab that t# and turn it into a variable, so I can log info in a file named t12345.txt or 12345.txt, either-or doesn't really matter, as long as it matches the topic number of the poll.
The numbers after the /t are the only thing that should change in this URL. There are currently 5 digits here, and I don't expect this to change any time soon.
My question is: How do I grab this t# from the URL and create a variable from it?
Thank you in advance!
Check out preg_match
preg_match('|/t[0-9]{5}|', $url, $matches);
if (count($matches)) {
$t_number = $matches[0]; // "/t12345"
$number = substr($t_number, 2, strlen($t_number)); // 12345
}
Assumptions:
1) The referring url will never have the pattern t#####. (t12345.com/vote)
2) You will always have five digits. (if this changes, you can do {5,6} to match 5-6 instances
Curtis already answered, but here's a non-regex alternative:
Use parse_url on the URL to get the "path".
Use explode with a comma delimiter to get your t# as array element 0 in the result.
(optional) Use explode on element 1 of the result from 2 with a delimiter of = to get "action" in element 0 and "vote" in element 1 of this new result.
Eg.
$url = "http://subdomain.sample.com/t12345,action=vote";
$url_pieces = parse_url($url);
$path = str_replace("/","",$url_pieces["path"]);
$args = explode(',',$path);
t_number_thingy = $args[0];
Edit: added str_replace as parse_url will include slash on the path.
Non regex solution (don't know about performance) and there is probably a better way but it works.
<?php
$var = "http://subdomain.sample.com/t12345,action=vote;";
$remove = "http://subdomain.sample.com/t";
$intCount = 5;
echo substr($var, strpos($var, $remove) + strlen($remove), $intCount);
?>
phpFiddle
You dont need to use regex on this you can also use str_replace(); and basename();
Like:
<?php
$ref = "http://subdomain.sample.com/t12345,action=vote";
if(substr($ref,-4)==="vote"){
$ref = basename(str_replace(',action=vote','',$ref));
}
echo $ref; //t12345
?>
Or a one liner:
$ref = (substr($ref,-4)==="vote") ? basename(str_replace(',action=vote','',$ref)) : "Unknown";
I'm trying to create a simple framework in PHP which will include a file (index.bel) and render the variables within the file. For instance, the index.bel could contain the following:
<h1>{$variable_name}</h1>
How would I achieve this without using eval or demanding the users of the framework to type index.bel like this:
$index = "<h1>{$variable_name}</h1>";
In other words: Is it possible to render the content of a file without using eval? A working solution for my problem is this:
index.php:
<?php
$variable_name = 'Welcome!';
eval ('print "'.file_get_contents ("index.bel").'";');
index.bel:
<h1>{$variable_name}</h1>
I know many have recommended you to add template engine, but if you want to create your own, easiest way in your case is use str_replace:
$index = file_get_contents ("index.bel");
$replace_from = array ('$variable_a', '$variable_b');
$replace_to = array ($var_a_value, $var_b_value);
$index = str_replace($replace_from,$replace_to,$index);
Now that is for simple variable replace, but you soon want more tags, more functionality, and one way to do things like these are using preg_replace_callback. You might want to take a look at it, as it will eventually make possible to replace variables, include other files {include:file.bel}, replace text like {img:foo.png}.
EDIT: reading more your comments, you are on your way to create own framework. Take a look at preg_replace_callback as it gives you more ways to handle things.
Very simple example here:
...
$index = preg_replace_callback ('/{([^}]+)}>/i', 'preg_callback', $index);
...
function preg_callback($matches) {
var_dump($matches);
$s = preg_split("/:/",$matches[1]); // string matched split by :
$f = 'func_'.strtolower($s[0]); // all functions are like func_img,func_include, ...
$ret = $f($s); // call function with all split parameters
return $ret;
}
function func_img($s) {
return '<img src="'.$s[1].'" />';
}
From here you can improve this (many ways), for example dividing all functionalities to classes, if you want.
Yes, this is possible, but why are you making your own framework? The code you provided clearly looks like Smarty Template. You could try to look how they did it.
A possible way to run those code is splitting them into pieces. You split on the dollar sign and the next symbol which is not an underscore, a letter or an number. Once you did that. You could parse it into a variable.
$var = 'variable_name'; // Split it first
echo $$var; // Get the given variable
Did you mean something like this?
How do I replace using the following code?
ereg_replace("%Data_Index\[.\]%", $this->resultGData[$key ][\\1], $var)
I want to replace the number in [] %Data_Index
to $this->resultGData[$key ][\\1] same %Data_Index
and how ex %Data_Index[1] = $this->resultGData[$key][1], $var);
replace number in %Data_Index[...........] in []
to $this->resultGData[$key ][............]
same number
Try the preg_replace() function with the e modifier instead:
preg_replace('/%Data_Index\[(\d+)\]%/e', '$this->resultGData[$key][\1]', $var);
Note that this function uses Perl-compatible regular expressions instead of POSIX-extended regular expression.
your question is a little bit hard to understand
the smartest way to replace what you are asking I believe would be using a cycle
for example if you know that $this->resultGData[$key ][] has 10 elements on them you could simply do this, asuming %Data_Index[1] (are you sure it isn't $Data_Index? i'll asume that) you can try the following
$total = count($this->resultGData[$key ]); //we get the total of elements in that key
for($i=0;$i<$total;$i++)
{
$Data_Index[$i] = $this->resultGData[$key][$i];
}
now if the $key changes, you'd need to do this for every $key :)
keep practicing your english, it's a really useful tool in the IT field :) (not that i'm very a good at it either :P)