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.
Related
Ok so here is what I am trying to do, I need a php function that I can pass 4 parameters.
1) A String (Containing Tokens with text between them)
2) A Start Token String Parameter
3) A Stop Token String Parameter
4) A DO NOT DELETE String Parameter
I want to pass a (1)long string to the function and have it remove all the multiple instances of the (2)Start Tokens and all the Text Until The (3)Stop Token, UNLESS the (4)Do NOT DELETE Parameter is present in that part of the String.
The Setup would be like this:
HERE is the way the function would be setup:
function CleanUpMyString($string-1, $start-2, $end-3, $keep-4){
// Working Code That Does The Work Here
}
The String That I could Pass To The Function May Look Like this examples:
$stringTEST = "This is the intro of the string, <<<This Part Would Be Deleted>>> in the next snippet of the string, <<<we will delete another part>>> This is going pretty well. <<<keep>We do not delete this part because of the added token part 'keep>'.>>> We will add some more rambling text here. Then we will add another snippet. <<<We will also delete this one.>>><<<keep>But in the end it is all good!>>>";
Assuming I called the function like this:
echo CleanUpMyString($stringTEST, '<<<', '>>>', 'keep>');
I would get the following output:
This is the intro of the string, in the next snippet of the string, This is going pretty well. We do not delete this part because of the added token part 'keep>'. We will add some more rambling text here. Then we will add another snippet. But in the end it is all good!
I have no control over the input string, so the tokens could occur anywhere in any number, and there is not rational order in which they may appear.
I really am not sure where to start. I took a look at this thread:
PHP function to delete all between certain character(s) in string
which I thought has been the closest thing to what I wanted, but I could not see how to extend the idea to my application. Any help would be seriously appreciated!
my suggestion is to use preg_replace_callback
<?php
function CleanUpMyString($string, $start, $end, $keep)
{
return preg_replace_callback(
'~' . preg_quote($start, '~') . '.+?' . preg_quote($end, '~') . '~',
function ($M) use ($start, $end, $keep) {
if (strpos($M[0], $keep)) {
return str_replace([$start, $end, $keep], '', $M[0]);
} else {
return '';
}
},
$string
);
}
$stringTEST = "This is the intro of the string, <<<This Part Would Be Deleted>>> in the next snippet of the string, <<<we will delete another part>>> This is going pretty well. <<<keep>We do not delete this part because of the added token part 'keep>'.>>> We will add some more rambling text here. Then we will add another snippet. <<<We will also delete this one.>>><<<keep>But in the end it is all good!>>>";
echo CleanUpMyString($stringTEST, '<<<', '>>>', 'keep>');
Hope this will help you out, Here i am using preg_match to gather all matching tokens from start to end and then we are iterating over matches to keep required portion of string and removing un-necessary part.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$stringTEST = "This is the intro of the string, <<<This Part Would Be Deleted>>> in the next snippet of the string, <<<we will delete another part>>> This is going pretty well. <<<keep>We do not delete this part because of the added token part 'keep>'.>>> We will add some more rambling text here. Then we will add another snippet. <<<We will also delete this one.>>><<<keep>But in the end it is all good!>>>";
echo CleanUpMyString($stringTEST, "<<<", ">>>", "keep>");
function CleanUpMyString($stringTEST, $start, $end, $keep)
{
$startQuotes= preg_quote($start);
$endQuotes= preg_quote($end);
preg_match_all("/$startQuotes.*?(?:$endQuotes)/", $stringTEST,$matches);
foreach($matches[0] as $key => $value)
{
if(stristr($value, $start.$keep)!==false)
{
$stringTEST= substr_replace($stringTEST,"",strpos($stringTEST, $start.$keep), strlen($start.$keep));;
$stringTEST= substr_replace($stringTEST,"",strpos($stringTEST, $end), strlen($end));
}
else
{
$stringTEST= str_replace($value, "", $stringTEST);
}
}
return $stringTEST;
}
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
How would I go about searching/matching for a paticular set of a characters in a filename, for example 3XYTPRQgz.pdf is the filename, I need to search for '3XYTPRQ', then if this string is found I simply want to output 'job completed', if its not there it will be set to queued. ( I want to do this for more than one file).
My thoughts on how to do this is, (I am struggling on the matching of the string part) :
<?php
if(match("7digitnumber) //then < not sure what function to use any tips?
if file_exists($7digitnumber/filename)
{
echo "completed";
}
else
{
echo "queued";
}
?>
Thanks for any help.
If you simply want to find out if a given string (your case "3XYTPRQ") is part of a longer string ("3XYTPRQgz.pdf") you can take a look at strstr.
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.
This is a follow-up question to the one I posted here (thanks to mario)
Ok, so I have a preg_replace statement to replace a url string with sometext, insert a value from a query string (using $_GET["size"]) and insert a value from a associative array (using $fruitArray["$1"] back reference.)
Input url string would be:
http://mysite.com/script.php?fruit=apple
Output string should be:
http://mysite.com/small/sometext/green/
The PHP I have is as follows:
$result = preg_replace('|http://www.mysite.com/script.php\?fruit=([a-zA-Z0-9_-]*)|e', ' "http://www.mysite.com/" .$_GET["size"]. "/sometext/" .$fruitArray["$1"]. "/"', $result);
This codes outputs the following string:
http://mysite.com/small/sometext//
The code seems to skip the value in $fruitArray["$1"].
What am I missing?
Thanks!
Well, weird thing.
Your code work's perfectly fine for me (see below code that I used for testing locally).
I did however fix 2 things with your regex:
Don't use | as a delimiter, it has meaning in regex.
Your regular expression is only giving the illusion that it works as you're not escaping the .s. It would actually match http://www#mysite%com/script*php?fruit=apple too.
Test script:
$fruitArray = array('apple' => 'green');
$_GET = array('size' => 'small');
$result = 'http://www.mysite.com/script.php?fruit=apple';
$result = preg_replace('#http://www\.mysite\.com/script\.php\?fruit=([a-zA-Z0-9_-]*)#e', ' "http://www.mysite.com/" .$_GET["size"]. "/sometext/" .$fruitArray["$1"]. "/"', $result);
echo $result;
Output:
Rudis-Mac-Pro:~ rudi$ php tmp.php
http://www.mysite.com/small/sometext/green/
The only thing this leads me to think is that $fruitArray is not setup correctly for you.
By the way, I think this may be more appropriate, as it will give you more flexibility in the future, better syntax highlighting and make more sense than using the e modifier for the evil() function to be internally called by PHP ;-) It's also a lot cleaner to read, IMO.
$result = preg_replace_callback('#http://www\.mysite\.com/script\.php\?fruit=([a-zA-Z0-9_-]*)#', function($matches) {
global $fruitArray;
return 'http://www.mysite.com/' . $_GET['size'] . '/sometext/' . $fruitArray[$matches[1]] . '/';
}, $result);
i write it again, i don't understand good where is the error, the evaluation of preg results is very weird in php
preg_replace(
'|http\://([\w\.-]+?)/script\.php\?fruit=([\w_-]+)|e'
, '"http://www.$1/".$_GET["size"]."/sometext/".$fruitArray["$2"]."/";'
, $result
);
It looks like you have forgotten to escape the ?. It should be /script.php\?, with a \? to escape properly, as in the linked answer you provided.
$fruitArray["\$1"] instead of $fruitArray["$1"]