$i = $result->fetch_assoc();
preg_replace("/\{(.*?)\}/", $i["$1"], $content);
Error - Undefined variable: $1
// $1 - 'string'; // result search preg_replace()
// $i['string'] = 'hello';
How right syntax will be for print 'hello'?
ok next time please spend a little more time on asking the question:
<?php
$i['string'] = 'zzzzzzzzzzzzzzzzzzzzzz';
$content = "test test test {string} testtesttesttesttest";
$x=preg_replace_callback("/\{(.*?)\}/", function($m) use($i){
return $i[$m[1]];
}, $content);
echo $x;
demo: http://codepad.viper-7.com/u29uKh
for this particular approach you need to use preg_replace_callback() requires PHP 5.3+
You can make your replacements faster using strtr. To do that, you only need an associative array, but this time, all keys must be enclosed between curly brackets.
$i = $result->fetch_assoc();
$keys = array_map(function($k) { return '{' . $k . '}'; }, array_keys($i));
$trans = array_combine($keys, $i);
$content = strtr($content, $trans);
A variable name can't start with a number in PHP. It must start with an underscore or letter.
Related
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 have a string that looks a little like this, world:region:bash
It divides folder names, so i can create a path for FTP functions.
However, i need at some points to be able to remove the last part of the string, so, for example
I have this world:region:bash
I need to get this world:region
The script wont be able to know what the folder names are, so some how it needs to be able to remove the string after the last colon.
$res=substr($input,0,strrpos($input,':'));
I should probably highlight that strrpos not strpos finds last occurrence of a substring in given string
$tokens = explode(':', $string); // split string on :
array_pop($tokens); // get rid of last element
$newString = implode(':', $tokens); // wrap back
You may want to try something like this:
<?php
$variable = "world:region:bash";
$colpos = strrpos($variable, ":");
$result = substr($variable, 0, $colpos);
echo $result;
?>
Or... if you create a function using this information, you get this:
<?php
function StrRemoveLastPart($string, $delimiter)
{
$lastdelpos = strrpos($string, $delimiter);
$result = substr($string, 0, $lastdelpos);
return $result;
}
$variable = "world:region:bash";
$result = StrRemoveLastPart($variable, ":");
?>
Explode the string, and remove the last element.
If you need the string again, use implode.
$items = array_pop(explode(':', $the_path));
$shotpath = implode(':', $items);
Use regular expression /:[^:]+$/, preg_replace
$s = "world:region:bash";
$p = "/:[^:]+$/";
$r = '';
echo preg_replace($p, $r, $s);
demo
Notice how $ which means string termination, is made use of.
<?php
$string = 'world:region:bash';
$string = implode(':', explode(':', $string, -1));
I am trying to parse following text in variable...
$str = 3,283,518(10,569 / 2,173)
And i am using following code to get 3,283,518
$arr = explode('(',$str);
$num = str_replace(',','',$arr[0]); //prints 3283518
the above $str is dynamic and sometimes it could be only 3,283,518(means w/o ()) so explode function will throw an error so what is the best way to get this value? thanks.
$str = "3,283,518(10,569 / 2,173)";
preg_match("/[0-9,]+/", $str, $res);
$match = str_replace(",", "", array_pop($res));
print $match;
This will return 3283518, simply by taking the first part of the string $str that only consists of numbers and commas. This would also work for just 3,283,518 or 3,283,518*10,569, etc.
Probably going to need more information from you about how dynamic $str really is but if its just between those values you could probably do the following
if (strpos($str, '(' ) !== false) {
$arr = explode('(',$str);
$num = str_replace(',','',$arr[0]);
} else {
//who knows what you want to do here.
}
If you are really sure about number format, you can try something like:
^([0-9]+,)*([0-9]+)
Use it with preg_match for example.
But if it is not a simple format, you should go with an arithmetic expressions parser.
Analog solution:
<?php
$str = '3,283,518(10,569 / 2,173)';
if (strstr($str, '('))
{
$arr = explode('(',$str);
$num = str_replace(',','',$arr[0]);
}
else
{
$num = str_replace(',','',$str);
}
echo $num;
?>
$string = 'test check one two test3';
$result = mb_eregi_replace ( 'test|test2|test3' , '<$1>' ,$string ,'i');
echo $result;
This should deliver: <test> check one two <test3>
Is it possible to get, that test and test3 was found, without using another match function ?
You can use preg_replace_callback instead:
$string = 'test check one two test3';
$matches = array();
$result = preg_replace_callback('/test|test2|test3/i' , function($match) use ($matches) {
$matches[] = $match;
return '<'.$match[0].'>';
}, $string);
echo $result;
Here preg_replace_callback will call the passed callback function for each match of the pattern (note that its syntax differs from POSIX). In this case the callback function is an anonymous function that adds the match to the $matches array and returns the substitution string that the matches are to be replaced by.
Another approach would be to use preg_split to split the string at the matched delimiters while also capturing the delimiters:
$parts = preg_split('/test|test2|test3/i', $string, null, PREG_SPLIT_DELIM_CAPTURE);
The result is an array of alternating non-matching and matching parts.
As far as I know, eregi is deprecated.
You could do something like this:
<?php
$str = 'test check one two test3';
$to_match = array("test", "test2", "test3");
$rep = array();
foreach($to_match as $val){
$rep[$val] = "<$val>";
}
echo strtr($str, $rep);
?>
This too allows you to easily add more strings to replace.
Hi following function used to found the any word from string
<?php
function searchword($string, $words)
{
$matchFound = count($words);// use tha no of word you want to search
$tempMatch = 0;
foreach ( $words as $word )
{
preg_match('/'.$word.'/',$string,$matches);
//print_r($matches);
if(!empty($matches))
{
$tempMatch++;
}
}
if($tempMatch==$matchFound)
{
return "found";
}
else
{
return "notFound";
}
}
$string = "test check one two test3";
/*** an array of words to highlight ***/
$words = array('test', 'test3');
$string = searchword($string, $words);
echo $string;
?>
If your string is utf-8, you could use preg_replace instead
$string = 'test check one two test3';
$result = preg_replace('/(test3)|(test2)|(test)/ui' , '<$1>' ,$string);
echo $result;
Oviously with this kind of data to match the result will be suboptimal
<test> check one two <test>3
You'll need a longer approach than a direct search and replace with regular expressions (surely if your patterns are prefixes of other patterns)
To begin with, the code you want to enhance does not seem to comply with its initial purpose (not at least in my computer). You can try something like this:
$string = 'test check one two test3';
$result = mb_eregi_replace('(test|test2|test3)', '<\1>', $string);
echo $result;
I've removed the i flag (which of course makes little sense here). Still, you'd still need to make the expression greedy.
As for the original question, here's a little proof of concept:
function replace($match){
$GLOBALS['matches'][] = $match;
return "<$match>";
}
$string = 'test check one two test3';
$matches = array();
$result = mb_eregi_replace('(test|test2|test3)', 'replace(\'\1\')', $string, 'e');
var_dump($result, $matches);
Please note this code is horrible and potentially insecure. I'd honestly go with the preg_replace_callback() solution proposed by Gumbo.
Say this is my string
$string = 'product[0][1][0]';
How could I use that string alone to actually get the value from an array as if I had used this:
echo $array['product'][0][1][0]
I've messed around with preg_match_all with this regex (/\[([0-9]+)\]/), but I am unable to come up with something satisfactory.
Any ideas? Thanks in advance.
You could use preg_split to get the individual array indices, then a loop to apply those indices one by one. Here's an example using a crude /[][]+/ regex to split the string up wherever it finds one or more square brackets.
(Read the [][] construct as [\]\[], i.e. a character class that matches right or left square brackets. The backslashes are optional.)
function getvalue($array, $string)
{
$indices = preg_split('/[][]+/', $string, -1, PREG_SPLIT_NO_EMPTY);
foreach ($indices as $index)
$array = $array[$index];
return $array;
}
This is prettttty hacky, but this will work. Don't know how much your array structure is going to change, either, this won't work if you get too dynamic.
$array = array();
$array['product'][0][1][0] = "lol";
$string = 'product[0][1][0]';
$firstBrace = strpos( $string, "[" );
$arrayExp = substr($string, $firstBrace );
$key = substr( $string, 0, $firstBrace );
echo $arrayExp, "<br>";
echo $key, "<br>";
$exec = "\$val = \$array['".$key."']".$arrayExp.";";
eval($exec);
echo $val;
What about using eval()?
<?php
$product[0][1][0] = "test";
eval ("\$string = \$product[0][1][0];");
echo $string . "\n";
die();
?>