Add spaces inside array values - php

how can i make this code display $anchor with spaces. I would have Text Anchor1 and Text Anchor two insitead of TextAnchor1 and TextAnchor2. Thank you
$currentsite = get_bloginfo('wpurl');
$sites = array(
'TextAnchor1' => 'http://www.mysite1.com',
'TextAnchor2' => 'http://www.mysite2.com'
);
foreach($sites as $anchor => $site)
{
if ( $site !== $currentsite ){echo '<li>'.$anchor.'</li>';}
}

So, as you $anchor values probably aren't hard-coded, I assume what you really need is a function that takes a string as an argument and inserts spaces before any capital letters or numbers.
function splitWords($s){
return trim(preg_replace('/([A-Z0-9])/', ' \1', $s));
}
Later, when writing output, instead of $anchor, you can use splitWords($anchor).

$sites = array(
'Text Anchor 1' => 'http://www.mysite1.com',
'Text Anchor 2' => 'http://www.mysite2.com'
);

Ooh, ooh, my turn.
$sites = array(
'Text Anchor 1' => 'http://www.mysite1.com',
'Text Anchor 2' => 'http://www.mysite2.com'
);

Just change to:
$sites = array(
'Text Anchor' => 'http://www.mysite1.com',
'My Text Anchor' => 'http://www.mysite2.com'
);

Related

Parsing html tags from php array in the response

Having the next array:
$link = 'Link ' . 'Learn more...';
$array = ['1' => 'normal string text', '2' => $link];
return $array;
The response would be:
1 "normal string text"
2 "Link, <a href="https://google.com">Learn more..."
The result expected would be that the a tag would get parsed:
Link, Learn more...
Tried with different solutions, but nothing seems to be working. Any ideas?
Thanks
Edited: The result should be an array in which one of the entries would be that link already parsed and ready to be used.
well you'r code is correct but you are returning the array outside a function
you need to add it to a function and call it
ex :
public function printArray(){
$link = 'Link ' . 'Learn more...';
$array = ['1' => 'normal string text', '2' => $link];
return $array;
}
//callback
echo printArray();
or if you want to pass some params
public function printArray($link , $text){
$link = $link;
$array = ['1' => $text, '2' => $link];
return $array;
}
//callback
$link = 'Link ' . 'Learn more...';
$text='normal string text';
echo printArray($link,$text);
or just print it like this:
$link = 'Link ' . 'Learn more...';
$array = ['1' => 'normal string text', '2' => $link];
print($array[0]);//output : normal string text
print($array[1]);//output : Link Learn more...
you can use :
$link = 'Link ' . 'Learn more...';
$elements = ['1' => 'normal string text', '2' => $link];
foreach($elements as $key => $element){
echo "{$key} {$element} <br>";
}
I don't know if this will work since I haven't tested it but you could try:
<?php
$array->data[] = array(
'Your text',
'<u>Learn more...</u>'
);
echo $array
?>

Replace variables from text with corresponding values

Let say I have the following string which I want to send as an email to a customer.
"Hello Mr/Mrs {{Name}}. You have subscribed for {{Service}} at {{Date}}."
And I have an array with the values that should be replaced
array(
'Name' => $customerName, //or string
'Service' => $serviceName, //or string
'Date' => '2015-06-06'
);
I can find all strings between {{..}} with this:
preg_match_all('/\{{(.*?)\}}/',$a,$match);
where $match is an array with values, But I need to replace every match with a corresponding value from an array with values
Note that the array with values contains a lot more values and the number of items in it or the keys sequence is not relevant to number of matches in string.
You can use preg_replace_callback and pass the array with the help of use to the callback function:
$s = "Hello Mr/Mrs {{Name}}. You have subscribed for {{Service}} at {{Date}} {{I_DONT_KNOW_IT}}.";
$arr = array(
'Name' => "customerName", //or string
'Service' => "serviceName", //or string
'Date' => '2015-06-06'
);
echo $res = preg_replace_callback('/{{(.*?)}}/', function($m) use ($arr) {
return isset($arr[$m[1]]) ? $arr[$m[1]] : $m[0]; // If the key is uknown, just use the match value
}, $s);
// => Hello Mr/Mrs customerName. You have subscribed for serviceName at 2015-06-06.
See IDEONE demo.
The $m[1] refers to what has been captured by the (.*?). I guess this pattern is sufficient for the current scenario (does not need unrolling as the strings it matches are relatively short).
You don't need to use a regex for that, you can do it with a simple replacement function if you change a little the array keys:
$corr = array(
'Name' => $customerName, //or string
'Service' => $serviceName, //or string
'Date' => '2015-06-06'
);
$new_keys = array_map(function($i) { return '{{' . $i . '}}';}, array_keys($corr));
$trans = array_combine($new_keys, $corr);
$result = strtr($yourstring, $trans);
Try
<?php
$str = "Hello Mr/Mrs {{Name}}. You have subscribed for {{Service}} at {{Date}}.";
$arr = array(
'Name' => 'some Cust', //or string
'Service' => 'Some Service', //or string
'Date' => '2015-06-06'
);
$replaceKeys = array_map(
function ($el) {
return "{{{$el}}}";
},
array_keys($arr)
);
$str = str_replace($replaceKeys, array_values($arr), $str);
echo $str;

Replace variable texts with regular expressions

I'm reformulating one of my old programs and using TextCrawler to automate text replacements in several code files, but I'm struggling to make the following change:
I need to find all 'text' functions (example):
$object->text('TRANSLATE_KEY_A')
$object->text('TRANSLATE_KEY_B')
...
and replace them with (example):
__('RETURNED_TEXT_FROM_TRANSLATE_KEY_A', TEXT_DOMAIN)
__('RETURNED_TEXT_FROM_TRANSLATE_KEY_B', TEXT_DOMAIN)
...
Where RETURNED_TEXT_FROM_TRANSLATE_KEY_X are set with the 'text' array's key in another code file
array_push($text, array('key' => 'TRANSLATE_KEY_A',
'extras' => '',
'text' => 'Translated Text A'));
array_push($text, array('key' => 'TRANSLATE_KEY_B',
'extras' => '',
'text' => 'Translated Text B'));
The final result should be:
$object->text('TRANSLATE_KEY_A')
$object->text('TRANSLATE_KEY_B')
...
replaced with
__('Translated Text A', TEXT_DOMAIN)
__('Translated Text B', TEXT_DOMAIN)
...
There are over 1500 of these :(
Is it possible to achieve this with regular expression in TextCrawler, and how? Or any other idea? Thanks
If you want to use a php array to provide the replacement data it is probably best to just use php itself for the task.
Example script.php:
// your $text array
$text = array();
array_push($text, array(
'key' => 'TRANSLATE_KEY_A',
'extras' => '',
'text' => 'Translated Text A')
);
array_push($text, array(
'key' => 'TRANSLATE_KEY_B',
'extras' => '',
'text' => 'Translated Text B')
);
...
// create a separate array from your $text array for easy lookup
$data_arr = array();
foreach ($text as $val) {
$data_arr[$val['key']] = $val['text'];
}
// your code file, passed as first argument
$your_code_file = $argv[1];
// open file for reading
$fh = fopen($your_code_file, "r");
if ($fh) {
while (($line = fgets($fh)) !== false) {
// check if $line has a 'text' function and if the key is in $data_arr
// if so, replace $line with the __(...) pattern
if (preg_match('/^\$object->text\(\'([^\']+)\'\)$/', $line, $matches)
&& isset($data_arr[$matches[1]])) {
printf("__('%s', TEXT_DOMAIN)\n", $data_arr[$1]);
} else {
print($line);
}
}
fclose($fh);
} else {
print("error while opening file\n");
}
Call:
php script.php your_code_file
Just add functionality to iterate over all of your code files and write to the corresponding output files.

How can I replace multiple strings within a string without overlapping results?

I'm trying to create common masks from a string like so:
012abc.d+e_fg~hijk => 012{start}.d+{middle}_fg~{end}jk
replace:
$arrFromTo = array(
'st' => '{pre}',
'abc' => '{start}',
'e' => '{middle}',
'hi' => '{end}',
'dd' => '{post}'
);
Instead I keep overlapping replacements and get something like this instead (using a loop of str_replace's):
012{{pre}art}.d+{mi{post}le}_fg~{end}jk
Because the st is found in the already replaced {start} and dd is found in {middle}.
How would you replace the following?
$str = 'abc.d+e_fg~hijk';
echo replace_vars($str); // Desired output: 012{start}.d+{middle}_fg~{end}kJ
I might misunderstand, but you don't seem to need regex for the replacing. They're simple, literal replacements.
$from = '012abc.d+e_fg~hijk';
$arrFromTo = array(
'st' => '{pre}',
'abc' => '{start}',
'e' => '{middle}',
'hi' => '{end}',
'dd' => '{post}'
);
$to = strtr($from, $arrFromTo); // 012{start}.d+{middle}_fg~{end}jk
strtr() is awesome. It takes a very readable input and it doesn't re-replace like your problem in the loop.
You can use preg_replace like this:
$str = '012abc.d+e_fg~hijk';
$arrFromTo = array(
'st' => '{pre}',
'abc' => '{start}',
'e' => '{middle}',
'hi' => '{end}',
'dd' => '{post}'
);
$reArr=array();
foreach($arrFromTo as $k=>$v){
$reArr['/' . $k . '(?![^{}]*})/'] = $v;
}
echo preg_replace(array_keys($reArr), array_values($reArr), $str);
//=> 012{start}.d+{middle}_fg~{end}jk
Core of this regex is this negative lookaead: (?![^{}]*})
Which avoid matching keys of array if it is enclosed in {...} since all the replacements are enclosed in {...}.
This will search the string for each replacement in order. If it finds one, it will split the string, and search the remainder of the string for any other replacements.
$str = '012abc.d+e_fg~hijk';
$rep = array(
'st' => '{pre}',
'abc' => '{start}',
'e' => '{middle}',
'hi' => '{end}',
'dd' => '{post}'
);
$searched = '';
foreach ($rep as $key => $r) {
if (strpos($str, $key) !== false) {
$searched .= substr($str, 0, strpos($str, $key)) . $r;
$str = substr($str, strpos($str, $key) + strlen($key));
}
}
$searched .= $str;
echo $searched; //012{start}.d+{middle}_fg~{end}jk
It will search and find them in the order that you have specified.

how to replace abusive words php

hello all i have a page where i need to replace all the occurrence of some particular words which may be abusive with a image (same image for all the words) and i have following function which does the work but it is case sensitive . like it replaces f*k but not f*k f*k f*k f**k etc.. and i think there is a better way to do this please help .
my function is
function filter($text) {
$icons = array(
'f**k ' => '<img src="smiles/filter.png" class="filter" title="Blured text "/>',
'something else' => '<img src="smiles/filter.png" class="filter" title="Blured text "/>',
' something else' => '<img src="smiles/filter.png" class="filter" title="f**k you ::F"/>'
);
return strtr($text, $icons);
}
You'd need a bigger filter based on RegEx for this
Like this:
function filterAbusiveWords( $string ) {
static $abusiveWords = array(
'/f[u]+c?k/i' => 'some icon',
'/f[\*]+c?k/i' => 'some icon',
'/f[a]+c?k/i' => 'some icon',
'/some normal word/i' => 'some icon'
);
return preg_replace( array_keys( $abusiveWords ), array_values( $abusiveWords ), $string );
}
This would (in theory) replace all occurences of fak, fuck, f**ck, f*k, faaak, fuk etc.

Categories