PHP regex replace from data array - php

I have a template string like this
$myStr ="<font face=\"#3#\" size=\"6\">TEST STRING</font>";
And an array of fonts like this
$fontList = array(
0 => "ubuntumono",
1 => "opensans",
2 => "opensanscondensed",
3 => 'opensanslight',
4 => 'exo2',
5 => 'exo2light'
);
Now I want to check my string for face=\"#3#\" (3 is the index of font in $fontList)
and replace it with face=\"opensanslight\"
How can I do it with Regex & PHP? Thank you.

Assuming PHP 5.3.0 or better:
$myStr = preg_replace_callback('/#(\d+)#/', function ($matches) use ($fontList) {
return $fontList[$matches[1]];
}, $myStr);
Example
If you want to only change #number# when it is surrounded by quotes:
$myStr = preg_replace_callback('/"#(\d+)#"/', function ($matches) use ($fontList) {
return '"' . $fontList[$matches[1]] . '"';
}, $myStr);
Example

Related

PHP - How to change specific word in string using array [duplicate]

This question already has an answer here:
Replace templates in strings by array values
(1 answer)
Closed 6 years ago.
$str = "Hello {{name}} welcome to {{company_name}}";
$array = ['name' => 'max', 'company_name' => 'Stack Exchange'];
how to replace {{name}} and {{company_name}} using array value. any php function that return output like
Hello max welcome to Stack Exchange
First create a new array with your search fields, wrapped in curly braces:
$searchArray = array_map(function($value) {
return "{{" . $value . "}}";
}, array_keys($array));
Now you have an array with the tokens you are searching for, and you already have an array of values you want to replace the tokens with.
So just do a simple str_replace:
echo str_replace($searchArray, $array, $str);
Working example: https://3v4l.org/8tPZt
Here's a tidy little function put together:
function fillTemplate($templateString, array $searchReplaceArray) {
return str_replace(
array_map(function($value) { return "{{" . $value . "}}"; }, array_keys($searchReplaceArray)),
$searchReplaceArray,
$templateString
);
}
Now you can call it like this:
echo fillTemplate(
"Hello {{name}} welcome to {{company_name}}",
['name' => 'max', 'company_name' => 'Stack Exchange']
);
// Hello max welcome to Stack Exchange
Example: https://3v4l.org/rh0KX
Checkout this nice function of PHP: http://php.net/manual/de/function.strtr.php
You can find there examples and explanation of it.
$str = "Hello {{name}} welcome to {{company_name}}";
$array = ['{{name}}' => 'max', '{{company_name}}' => 'Stack Exchange'];
print strtr ($str, $array);

Correct regex to detect font family names from google font link src

I've been trying to get array of the fonts that I'm enqeueing on my wordpress theme. This is just for testing.
On input:
http://fonts.googleapis.com/css?family=Arimo:400,700|Quicksand:400,700|Cantarell:400,700,400italic,700italic|Muli:300,400,300italic,400italic|Roboto+Slab:400,700|Share:400,700,400italic,700italic|Inconsolata:400,700|Karla:400,700,400italic,700italic|Maven+Pro:400,500,700,900|Roboto+Slab:400,700|Open+Sans:400italic,600italic,700italic,400,600,700
What I need on output is like this:
array(
[0] => 'Arimo',
[1] => 'Quicksand',
[2] => 'Cantarell',
... so on
)
Till now, I have done almost everything but one little problem.
My code:
$input = 'http://fonts.googleapis.com/css?family=Arimo:400,700|Quicksand:400,700|Cantarell:400,700,400italic,700italic|Muli:300,400,300italic,400italic|Roboto+Slab:400,700|Share:400,700,400italic,700italic|Inconsolata:400,700|Karla:400,700,400italic,700italic|Maven+Pro:400,500,700,900|Roboto+Slab:400,700|Open+Sans:400italic,600italic,700italic,400,600,700';
$against = "/[A-Z][a-z]+[\+][A-Z][a-z]+|[A-Z][a-z]+/";
$matches = array()
preg_match_all( $against, $input, $matches );
print_r($matches);
From this, the output is like this:
array(
0 => Arimo
1 => Quicksand
2 => Cantarell
3 => Muli
4 => Roboto+Slab
5 => Share
6 => Inconsolata
7 => Karla
8 => Maven+Pro
9 => Roboto+Slab
10 => Open+Sans
)
There's the + sign where the font name has spaces. I want to get rid of that.
I'm not a regex expert. So, couldn't manage to do that.
Note: I know I could do it with str_replace() but don't want to go through that long process. I want to know if it's possible to escape the + sign through and leave an empty space there when we are collecting matched expressions.
Spaces encoded as plus (+) signs in url. You should decode your url.
$input = urldecode($input);
Without regex:
$query = strtr(substr(parse_url($url, PHP_URL_QUERY),7), '+', ' ');
$result = array_map(function ($i) { return explode(':', $i)[0]; }, explode('|', $query));
With regex:
if (preg_match_all('~(?:\G(?!\A)|[^?&]+[?&]family=)([^:|&]+):[^:|&]*(?:[|&#]|\z)~', strtr($url, '+', ' '), $m))
$result2 = $m[1];
From your code, output is given me something like this.
array([0] => array([0] => Arimo[1] => Quicksand[2] => Cantarell[3] => Muli[4] => Roboto+Slab[5] => Share[6] => Inconsolata[7] => Karla[8] => Maven+Pro[9] => Roboto+Slab[10] => Open+Sans))
if is correct, then i was solve this issue '+'. here is the solution.
$input = 'http://fonts.googleapis.com/css?family=Arimo:400,700|Quicksand:400,700|Cantarell:400,700,400italic,700italic|Muli:300,400,300italic,400italic|Roboto+Slab:400,700|Share:400,700,400italic,700italic|Inconsolata:400,700|Karla:400,700,400italic,700italic|Maven+Pro:400,500,700,900|Roboto+Slab:400,700|Open+Sans:400italic,600italic,700italic,400,600,700';
$against = "/[A-Z][a-z]+[\+][A-Z][a-z]+|[A-Z][a-z]+/";
$matches = array();
$newArr=array();
preg_match_all( $against, $input, $matches );
for($i=0;$i< count($matches);$i++){
for($j=0;$j< count($matches[$i]);$j++){
$string=preg_replace('/[^A-Za-z0-9\-]/', ' ', $matches[$j]);
if($string!=""){
$newArr[]=$string;
}
}
}
print_r($newArr);
In general, you have more than + characters to worry about.
Special characters, such as the ampersand (&), and non-ASCII characters in URL query parameters have to be escaped using percent-encoding (%xx). In addition, when an HTML form is submitted, spaces are encoded using the + character.
For example:
The font family "Jacques & Gilles" would be escaped as:
Jacques+%26+Gilles
The Unicode character U+1E99 (LATIN SMALL LETTER Y WITH RING ABOVE), serialized into octets as UTF-8 (E1 BA 99), would be escaped as:
%e1%ba%99
To do what you want properly, you have to extract the query string from the URL, and use parse_str() to extract the name=value pairs. The parse_str() function will automatically urldecode() the names and values including the + characters.
First, split the URL on the ? character to extract the query string:
$url = 'http://fonts.googleapis.com/css?family=Arimo:400,700|...|Maven+Pro:400,500,700,900|Roboto+Slab:400,700|...';
$a = explode ('?', $url, 2);
if (isset ($a[1])) {
$query = $a[1];
}
You can also use parse_url ($url, PHP_URL_QUERY), but it doesn't buy you much in this case.
Then extract all the parameters:
if (isset ($query)) {
parse_str ($query, $params);
if (isset ($params['family'])) {
/* OK: Extract family names. */
} else {
/* Error: No family parameter found. */
}
} else {
/* Error: No query string found. */
}
Note: You should always specify the second parameter of parse_str() to avoid clobbering existing variables.

One regex, multiple replacements [duplicate]

This question already has answers here:
Parse through a string php and replace substrings
(2 answers)
Closed 9 years ago.
OK, that's what I need :
Get all entries formatted like %%something%%, as given by the regex /%%([A-Za-z0-9\-]+)%%/i
Replace all instances with values from a table, given the index something.
E.g.
Replace %%something%% with $mytable['something'], etc.
If it was a regular replacement, I would definitely go for preg_replace, or even create an array of possible replacements... But what if I want to make it a bit more flexible...
Ideally, I'd want something like preg_replace($regex, $mytable["$1"], $str);, but obviously it doesn't look ok...
How should I go about this?
Code:
<?php
$myTable = array(
'one' => '1!',
'two' => '2!',
);
$str = '%%one%% %%two%% %%three%%';
$str = preg_replace_callback(
'#%%(.*?)%%#',
function ($matches) use ($myTable) {
if (isset($myTable[$matches[1]]))
return $myTable[$matches[1]];
else
return $matches[0];
},
$str
);
echo $str;
Result:
1! 2! %%three%%
if you don't want to tell upper from lower,
<?php
$myTable = array(
'onE' => '1!',
'Two' => '2!',
);
$str = '%%oNe%% %%twO%% %%three%%';
$str = preg_replace_callback(
'#%%(.*?)%%#',
function ($matches) use ($myTable) {
$flipped = array_flip($myTable);
foreach ($flipped as $v => $k) {
if (!strcasecmp($k, $matches[1]))
return $v;
}
return $matches[1];
},
$str
);
echo $str;

Fastest way to replace string patterns by mask

I have string like
$string = "string_key::%foo%:%bar%";
, and array of params
$params = array("foo" => 1, "bar" => 2);
How can I replace this params in $string pattern?
Expected result is
string_key::1:2
First, you need to rewrite the $params array:
$string = "string_key::%foo%:%bar%";
$params = array("foo" => 1, "bar" => 2);
foreach($params as $key => $value) {
$search[] = "%" . $key . "%";
$replace[] = $value;
}
After that, you can simply pass the arrays to str_replace():
$output = str_replace($search, $replace, $string);
View output on Codepad
On a personal note, I did this one:
$string = "string_key::%foo%:%bar%";
$params = array("%foo%" => 1, "%bar%" => 2);
$output = strtr($string, $params);
You do not have to do anything else because if there is some value in the array or the string is not replaced and overlooked.
Fast and simple method for pattern replacement.
I'm not sure what will be the fastest solution for you (it depends on the string size and the number of replacement values you will use).
I normally use this kind of function to perform parameterized replacements. It uses preg_replace_callback and a closure to perform the replacement for each percent enclosed word.
function replaceVariables($str, $vars)
{
// the expression '/%([a-z]+)%/i' could be used as well
// (might be better in some cases)
return preg_replace_callback('/%([^%]+)%/', function($m) use ($vars) {
// $m[1] contains the word inside the percent signs
return isset($vars[$m[1]]) ? $vars[$m[1]] : '';
}, $str);
}
echo replaceVariables("string_key::%foo%:%bar%", array(
"foo" => 1,
"bar" => 2
));
// string_key::1:2
Update
It's different from using str_replace() in cases whereby a percent enclosed value is found without a corresponding replacement.
This line determines the behaviour:
return isset($vars[$m[1]]) ? $vars[$m[1]] : '';
It will replace '%baz%' with an empty string if it's not part of the $vars. But this:
return isset($vars[$m[1]]) ? $vars[$m[1]] : $m[0];
Will leave '%baz%' in your final string.

Search an Array and remove entry if it doesn't contain A-Z or a A-Z with a dash

I have the following Array:
Array
(
[0] => text
[1] => texture
[2] => beans
[3] =>
)
I am wanting to get rid of entries that don't contain a-z or a-z with a dash. In this case array item 3 (contains just a space).
How would I do this?
Try with:
$input = array( /* your data */ );
function azFilter($var){
return preg_match('/^[a-z-]+$/i', $var);
}
$output = array_filter($input, 'azFilter');
Also in PHP 5.3 there is possible to simplify it:
$input = array( /* your data */ );
$output = array_filter($input, function($var){
return preg_match('/^[a-z-]+$/i', $var);
});
Try:
<?php
$arr = array(
'abc',
'testing-string',
'testing another',
'sdas 213',
'2323'
);
$tmpArr = array();
foreach($arr as $str){
if(preg_match("/^([-a-z])+$/i", $str)){
$tmpArr[] = $str;
}
}
$arr = $tmpArr;
?>
Output:
array
0 => string 'abc' (length=3)
1 => string 'testing-string' (length=14)
For the data you have provided in your question, use the array_filter() function with an empty callback parameter. This will filter out all empty elements.
$array = array( ... );
$array = array_filter($array);
If you need to filter the elements you described in your question text, then you need to add a callback function that will return true (valid) or false (invalid) depending on what you need. You might find the ctype_alpha functions useful for that.
$array = array( ... );
$array = array_filter($array, 'ctype_alpha');
If you need to allow dashes as well, you need to provide an own function as callback:
$array = array( ... );
$array = array_filter($array, function($test) {return preg_match('(^[a-zA-Z-]+$)', $test);});
This sample callback function is making use of the preg_match() function using a regular expression. Regular expressions can be formulated to represent a specifc group of characters, like here a-z, A-Z and the dash - (minus sign) in the example.
Ok , simply you can loop trough the array. Create an regular expression to test if it matches your criteria.If it fails use unset() to remove the selected element.

Categories