Dynamic str_replace vars (without knowing the name) - php

I have a DB with pages with some variabiles in the content, for exmpale [var1], [name], [foo],..
Example of page:
hi [name],
are you [var1] or [foo]?
All these variables should be replaced with the corrisponding php variabiles on output
[var1] become $var1
[name] become $name
I know that i can use str_replace manually to change this variabiles, for example:
echo( str_replace( array( [var1], [name], [foo] ), array( $var1, $name, $foo), $page ));
But there is a way to create a loop that automatically replaces all these vars?

Let us consider an array containing some string as follows:
array("var1","name","foo")
So here is the solution:
<?php
$rowdata=array("var1","name","foo");
foreach($rowdata as $key=>$value){
$rowdata[$key]="$".$value;
}
echo '<pre>';
print_r($rowdata);
echo '</pre>';
?>

Try this code. It is working. First of all find all such strings which are in bracket. and then use the preg_replace to replace the content.
$text = '[This] is a [test] string, [try] it.';
preg_match_all("^\[(.*?)\]^", $text, $matches);
$data = array_combine($matches[1],$matches[1]);
foreach($data as $key =>$value)
{
$text = preg_replace('/\['.$key.'\]/', '$'.$value, $text);
}
echo $text;

Related

Shortcode style parsing

Looking at how WP uses shortcodes I thoufght I could implement the same structure into a project, I assumed this would be availble somwehere but have yet to track down.
I started to parse myself starting with a preg_match_all
preg_match_all('/[[^]]*]/', $content, $match);
and that return the array with all the shortcodes inside content as expected but then looking at parsing the name, variables or array keys with values I start getting real heavy on parsing.
My current thought is to break up on spaces, then parse each but then i run into spaces in the values even though they are in quotes. So if i parse quoted data first then spaces to re-construct it seems very wasteful. I don't need to re-invent the wheel here so any input is fantastic.
example
[shortcodename key1="this is a value" key2="34"]
would like to have
Array
(
[shortcodename] => Array
(
[key1] => this is a value
[key2] => 34
)
)
here is the complete function that is working if anyone else is looking to do the same, obviously this is not meant to run user content but the called function should do any checks as this only replaces the shortcode if the funtction has a return value.
function processShortCodes($content){ // locate data inside [ ] and
//process the output, place back into content and returns
preg_match_all('/\[[^\]]*\]/', $content, $match);
$regex = '~"[^"]*"(*SKIP)(*F)|\s+~';
foreach ($match[0] as $key => $val){
$valOrig = $val; // keep uncleaned value to replace later
$val = trim(substr($val, 1, -1));
$replaced = preg_replace($regex,":",$val);
$exploded = explode(':',$replaced);
if (is_array($exploded)){
$fcall = array();
$fcallName = array_shift($exploded); // function name
if (function_exists($fcallName)){ // If function exsist then go
foreach ($exploded as $aKey => $aVal){
$arr = explode("=", $aVal);
if (substr($arr[1], 0, 1) == '&'){
$fCall[$arr[0]]=substr($arr[1], 6, -6); // quotes can be "
}else{
$fCall[$arr[0]]=substr($arr[1], 1, -1);
}
}
if ( is_array($fCall) && $fcallName ){
$replace = call_user_func($fcallName, $fCall);
if ($replace){
$content = str_replace($valOrig,$replace,$content);
}
}
}
}
}
You can try this to change all spaces not wrapped in quotes to let's say a semicolon then explode by semicolon
$regex = '~"[^"]*"(*SKIP)(*F)|\s+~';
$subject = 'hola hola "pepsi cola" yay';
$replaced = preg_replace($regex,";",$subject);
$exploded = explode(';', $replaced);
Credits

How do i get each expected string from a multiple string line

I dont really no how to start my steatment to output my expected result but in my achievement i have a hug string characters line example
$string = 'newboy1fineboy8badboy12 boy4andothers...';
my problem is how do i get all the boy and related characters from the string line example:
my expected result should be boy1boy8boy12boy4
Big thanks for time and impact in my solution
You can use preg_match_all and then foreach to display all data as per your requirement like below:
<?PHP
$string = 'newboy1fineboy8badboy12 boy4andothers...';
$string = preg_match_all('/boy\d+/', $string, $results);
foreach($results[0] as $val){
echo $val;
echo "<br>";
}
// Output
boy8
boy12
boy4
?>
Or if you want to get all your required data in 1 string then like below:
foreach($results[0] as $val){
$updated_string .= $val;
$updated_string .= " ";
}
echo $updated_string;
// Output
boy8 boy12 boy4
If you want to get data like runboy8 runboy12 runboy4 then you have to use str_replace like below to further update your string:
$updated_string = str_replace("boy","runboy",$string);
// Output will be runboy8 runboy12 runboy4
You can use preg_match_all() to do that:
<?php
$string = 'newboy1fineboy8badboy12 boy4andothers...';
preg_match_all('/boy\d+/', $string, $results);
print_r($results);
Then you can access the list of matching strings as $results[0]:
Array
(
[0] => Array
(
[0] => boy1
[1] => boy8
[2] => boy12
[3] => boy4
)
)

Split string using regular expression in php

I'm beginner in php and I have string like this:
$test = http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg
And I want to split string to array like this:
Array(
[0] => http://localhost/biochem/wp-content/uploads//godzilla-article2.jpg
[1] => http://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg
)
What should I do?
$test = 'http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg';
$testurls = explode('http://',$test);
foreach ($testurls as $testurl) {
if (strlen($testurl)) // because the first item in the array is an empty string
$urls[] = 'http://'. $testurl;
}
print_r($urls);
You asked for a regex solution, so here you go...
$test = "http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg";
preg_match_all('/(http:\/\/.+?\.jpg)/',$test,$matches);
print_r($matches[0]);
The expression looks for parts of the string the start with http:// and end with .jpg, with anything in between. This splits your string exactly as requested.
output:
Array
(
[0] => http://localhost/biochem/wp-content/uploads//godzilla-article2.jpg
[1] => http://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg
)
you can split them if they are always like this vith substr() function reference: http://php.net/manual/en/function.substr.php but if they are dynamic in lenght. you need to get a ; or any other sign that is not likely to be used there before 2nd "http://" and then use explode function reference: http://php.net/manual/en/function.explode.php
$string = "http://something.com/;http://something2.com"; $a = explode(";",$string);
Try the following:
<?php
$temp = explode('http://', $test);
foreach($temp as $url) {
$urls[] = 'http://' . $url;
}
print_r($urls);
?>
$test = 'http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jp';
array_slice(
array_map(
function($item) { return "http://" . $item;},
explode("http://", $test)),
1);
For answering this question by regular expression I think you want something like this:
$test = "http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg";
$keywords = preg_split("/.http:\/\//",$test);
print_r($keywords);
It returns exactly something you need:
Array
(
[0] => http://localhost/biochem/wp-content/uploads//godzilla-article2.jp
[1] => localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg
)

Convert string into array using php

I am trying to generate the array structure as coding style so it can be used for further development for that purpose i have used following:
function convertArray($string)
{
$finalString = var_export($string, true);
return stripslashes($finalString);
}
It worked fine but the problem is that it adds the additional quotes to the start and end of the value how can i remove these quotes.
Example generated string is as follows:
array (
'foo' => 'array('foo','bar','baz')',
'bar' => 'array('foo','bar')',
'baz' => 'array('foo','bar')',
);
The string i need is:
array (
'foo' => array('foo','bar','baz'),
'bar' => array('foo','bar'),
'baz' => array('foo','bar'),
);
UPDATE
Here is how i create my array:
foreach( $attributes as $attrib )
{
if( $attrib->primary_key == '1' )
$column[$attrib->name] = array("'$attrib->type'", "'$attrib->max_length'", '\'pk\'');
else
$column[$attrib->name] = array("'$attrib->type'", "'$attrib->max_length'");
$string[$attrib->name] = 'array('.implode(',', $column[$attrib->name]).')';
}
after processing from this loop the final array sent to the above function to convert it into my desired form/
And you can use backslashes
$string = "Some text \" I have a double quote";
$string1 = 'Second text \' and again i have quote in text';
And lost variant
You can use 1 idiot variant to create many lines string an in example:
$string = <<<HERE
Many many text
HERE;
But i dont recommend use this variant
try to use trim.
Example:
$string = "'text with quotes'";
echo $string; // output: 'text with quotes'
echo trim($string, array("'")); // output: text with quotes

Replace names in text with links

I want to replace names in a text with a link to there profile.
$text = "text with names in it (John) and Jacob.";
$namesArray("John", "John Plummer", "Jacob", etc...);
$LinksArray("<a href='/john_plom'>%s</a>", "<a href='/john_plom'>%s</a>", "<a href='/jacob_d'>%s</a>", etc..);
//%s shout stay the the same as the input of the $text.
But if necessary a can change de array.
I now use 2 arrays in use str_replace. like this $text = str_replace($namesArray, $linksArray, $text);
but the replace shout work for name with a "dot" or ")" or any thing like that on the end or beginning. How can i get the replace to work on text like this.
The output shout be "text with names in it (<a.....>John</a>) and <a ....>Jacob</a>."
Here is an example for a single name, you would need to repeat this for every element in your array:
$name = "Jacob";
$url = "<a href='/jacob/'>$1</a>";
$text = preg_replace("/\b(".preg_quote($name, "/").")\b/", $url, $text);
Try something like
$name = 'John';
$new_string = preg_replace('/[^ \t]?'.$name.'[^ \t]/', $link, $old_string);
PHP's preg_replace accepts mixed pattern and subject, in other words, you can provide an array of patterns like this and an array of replacements.
Done, and no regex:
$text = "text with names in it (John) and Jacob.";
$name_link = array("John" => "<a href='/john_plom'>",
"Jacob" => "<a href='/jacob'>");
foreach ($name_link as $name => $link) {
$tmp = explode($name, $text);
if (count($tmp) > 1) {
$newtext = array($tmp[0], $link, $name, "</a>",$tmp[1]);
$text = implode($newtext);
}
}
echo $text;
The links will never change for each given input, so I'm not sure whether I understood your question. But I have tested this and it works for the given string. To extend it just add more entries to the $name_link array.
Look for regular expressions. Something like preg_replace().
preg_replace('/\((' . implode('|', $names) . ')\)/', 'link_to_$1', $text);
Note that this solution takes the array of names, not just one name.

Categories