Dear programmers and code freaks,
I've got this function
<?php
function ListRow($name) {
preg_match_all("'{row name ='".$name."'}(.*?){\/row}'si", $this->tpl, $match);
return $match[1];
}
?>
What it is supposed to do is getting the info between {row name = 'products'} and {/row}.
It does get the data between the tags if they're on the same line, but with enters between
them, it doesn't capture anything. I'm kinda stuck in this one so i would appreciate some help
more then anything.
This works, for me (see the "return" line, it's the only difference with your code...):
<?php
print ListRow("abc");
function ListRow($name) {
preg_match_all("/{row name ='".$name."'(.*?){\/row}/si", "{row name ='abc'
TEXT_SEARCHED
{/row}", $match);
return $match[1][0];
}
?>
And now, let's test it...:
$ php test.php
TEXT_SEARCHED
Related
Suppose, I have a string '#[52:] loves his mother very much'. I want the string to be replaced with 'Allen loves his mother very much'.
Explanation: when any match found in my string with syntax '#[numeric_id:]' then these matches will be replaced with the name of the user exist with the 'numeric_id' in 'user_entry' table. If match found in the string but no user found with the numeric_id in 'user_entry' table then it will return the exact string like '#[52:] loves his mother very much'.
I tried to do it with 'preg_replace' function in php. 'preg_replace' successfully collects all matches with syntax '#[numeric_id:]' but it can't send matches to a user defined function named 'test()'. In short my code does not working.
I have the following code in test.php file: .
<?php
function test($v) { $con=mysqli_connect("mysql14.000webhost.com","a8622422_jhon","pjdtmw7","a8622422_person");
$safe_id=preg_replace("/[^0-9]/",'',$v);
$sql="SELECT * FROM user_entry WHERE u_id='$safe_id'";
$result=mysqli_query($con,$sql);
$count=mysqli_num_rows($result); $found='';
if ($count==1) {
$row=mysqli_fetch_array($result);
$found=$row['name'];
} else { $found=$v; } return $found;
} ?>
<?php
$post='#[61150631867349144:] & #[59670019475743176:] are friends';
echo preg_replace('/(#\[[0-9]+\:+\]+)/',test('$1'),$post);
?>
I think, the code should return: 'Baki Billah, Mahfuzur rahman and mahi are friends'. But it returns: '#[61150631867349144:] & #[59670019475743176:] are friends'.
How can I do that? What's wrong with my code? Is there any way to do it? If it is impossible to do the action with above code, then please give me the correct & full code of test.php file so that I can do the action explained in the first part of my question.
Any help will be strongly appreciated (I'm working with php).
Thanks in advance.
If you want to execute code for each match of a regular expression the best way is to use the preg_replace_callback function. It can take the same pattern as you are using now but will call a given function for each match.
For example:
echo preg_replace_callback('/(#\[[0-9]+\:+\]+)/', 'test', $post);
You will need to modify your test function the receive an array of sub-matches. $v[0] will be the entire string match.
I'm editing a PHP file to replace a function's code by another code provided.
My problem is that the function's code may change. So, I don't know exactly how I should do the regex to find it.
Here's an example:
function lol()
{
echo('omg');
$num=0;
while($num<100)
{
echo('ok');
}
}
function teste()
{
echo('ola');
while($num<100)
{
echo('ok');
}
}
function test()
{
echo('oi');
while($num<100)
{
echo('ok');
}
}
What I need is to get the code of function teste(), which would be:
echo('ola');
while($num<100)
{
echo('ok');
}
BUT: I do not know how many whiles, foreaches or how many brackets are inside the functions, neither I don't know it's order. The example was just an example.
How would I be able to get the function's code?
Thank you in advance.
Disclaimer
As other users stated, this is probably not a good approach. And if you decided to use it anyway, double-check your result as regex can be treacherous.
Ugly solution
You can you something like to match even if the function is the last one (#Nippey):
(?:function teste\(\))[^{]*{(.*?)}[^}]*?(?:function|\Z)
Note: I'm using (?:xyz) which is for non-capturing parentheses group. Check if your regex engine support it.
Output
echo('ola');
while($num<100)
{
echo('ok');
}
Using recursive pattern (?R) you can match nested brackets:
$result = preg_replace_callback('#(.*?)\{((?:[^{}]|(?R))*)\}|.*#si', function($m){
if(isset($m[1], $m[2]) && preg_match('#function\s+teste\b#i', $m[1])){
return $m[2];
}
}, $code); // Anonymous function is used here which means PHP 5.3 is required
echo $result;
Online demo
I know a bit about Regular Expression but really want to learn more about it and now i'm trying to make a function that detects all {} in my content (from a database) and checks what between the brackets. If there is a POST or GET with a name (format: POST:name or GET:name} i would like to replace them with that value.
Example:
When i have a form with the following inputs:
Name
Email
Message
And then in the value attribute i type: {POST:Name}
Then the script must detect the {POST:Name} and will replace it with the string in $_POST['name']. I already searched on Google, but found too much that i don't know what to really use.
Now i have:
<?php
preg_match_all("/{(POST|GET):[.*](})/", $content, $matches, PREG_SET_ORDER);
foreach($matches AS $match)
{
if(isset($_POST[$match]))
$content = str_replace('{POST:'.$match, $_POST[$match], $content);
else
$content = str_replace('{GET:'.$match, $_GET[$match], $content);
}
?>
But this don't work.
You should use preg_replace, better than str_replace.
And if you use preg_replace, you don't need no more your first condition, et can do the same code with only one instruction.
http://fr2.php.net/preg_replace
<?php preg_replace('#{(POST|GET):(.*)}#','$_$1[$2]',$content); ?>
My regex can be false, but something like this should work.
hello i have a variable that has the text below:
<p>Not sure exactly which property you want to extract, but I assume it's the 'question_answers_url'.</p>
<pre><code>$answersArray = Array();
for($i=0;$i<count($jsonArray['questions']);$i++){
//assuming it is the 'question_answers_url' property that you want
array_push($answersArray,$jsonArray['questions'][$i]['question_answers_url']);
}
</code></pre>
<p>Ought to do it.</p>
how can i get only the text that is between <p>TEXT_I_WANT</p> and trash everything else.
preg_match_all("/<p>(.*?)<\/p>/is",$text,$matches,PREG_SET_ORDER);
foreach($maches as $match){
echo $match[1];
}
Untested !!
Updated!
I would like to know if it's possible to execute the php code in a string. I mean if I have:
$string = If i say <?php echo 'lala';?> I wanna get "<?php echo 'dada'; ?>";
Does anybody knows how?
[EDIT] It looks like nobody understood. I wanna save a string like
$string = If i say <?php count(array('lala'));?>
in a database and then render it. I can do it using
function render_php($string){
ob_start();
eval('?>' . $string);
$string = ob_get_contents();
ob_end_clean();
return $string;
}
The problem is that I does not reconize php code into "" (quotes) like
I say "<?php echo 'dada'; ?>"
$string = ($test === TRUE) ? 'lala' : 'falala';
There are lots of ways to do what it looks like you're trying to do (if I'm reading what you wrote correctly). The above is a ternary. If the condition evaluates to true then $string will be set to 'lala' else set to 'falala'.
If you're literally asking what you wrote, then use the eval() function. It takes a passed string and executes it as if it were php code. Don't include the <?php ?> tags.
function dropAllTables() {
// drop all tables in db
}
$string = 'dropAllTables();';
eval($string); // will execute the dropAllTables() function
[edit]
You can use the following regular expression to find all the php code:
preg_match_all('/(<\?php )(.+?)( \?>)/', $string, $php_code, PREG_OFFSET_CAPTURE);
$php_code will be an array where $php_code[0] will return an array of all the matches with the code + <?php ?> tags. $php_code[2] will be an array with just the code to execute.
So,
$string = "array has <?php count(array('lala')); ?> 1 member <?php count(array('falala')); ?>";
preg_match_all('/(<\?php )(.+?)( \?>)/', $string, $php_code, PREG_OFFSET_CAPTURE);
echo $php_code[0][0][0]; // <?php count(array('lala')); ?>
echo $php_code[2][0][0]; // count(array('lala'));
This should be helpful for what you want to do.
Looks like you are trying to concatenate. Use the concatenation operator "."
$string = "if i say " . $lala . " I wanna get " . $dada;
or
$string = "if i say {$lala} I wanna get {$dada}.";
That is what I get since your string looks to be a php variable.
EDIT:
<?php ?> is used when you want to tell the PHP interpreter that the code in those brackets should be interpreted as PHP. When working within those PHP brackets you do not need to include them again. So as you would just do this:
// You create a string:
$myString = "This is my string.";
// You decide you want to add something to it.
$myString .= getMyNameFunction(); // not $myString .= <?php getMyNameFunction() ?>;
The string is created, then the results of getMyNameFunction() are appended to it. Now if you declared the $myString variable at the top of your page, and wanted to use it later you would do this:
<span id="myString"><?php echo $myString; ?></span>
This would tell the interpreter to add the contents of the $myString variable between the tags.
Use token_get_all() on the string, then look for a T_OPEN_TAG token, start copying from there, look for a T_CLOSE_TAG token and stop there. The string between the token next to T_OPEN_TAG and until the token right before T_CLOSE_TAG is your PHP code.
This is fast and cannot fail, since it uses PHP's tokenizer to parse the string. You will always find the bits of PHP code inside the string, even if the string contains comments or other strings which might contain ?> or any other related substrings that will confuse regular expressions or a hand-written, slow, pure PHP parser.
I would consider not storing your PHP code blocks in a database and evaluating them using eval. There is usually a better solution. Read about Design Pattern, OOP, Polymorphism.
You could use the eval() function.