String translate from Array , str_replace? - php

String translate from Array , str_replace?
I have an array
$money = array(
"USD"=>100,
"BAT"=>1000,
"RIEL"=>2000
);
And I define as constant to be translate:
define("const_infor","Your __TYPE__ are: __AMOUNT__ __CURRENCY__ .<br><br>");
Bad WAYS:
echo "Your balance are :";//more constant here
foreach ($money as $currency=>$amount){
echo $money.$currency."; ";
}
I try to output(GOOD WAYS):
$tmp1 = "";
$tmp2 = "";
foreach ($money as $currency=>$amount){
$tmp1 .= $money;
$tmp2 .= $currency;
}
echo str_replace(ARRAY("__TYPE__","__AMOUNT__","__CURRENCY__"),ARRAY("Balance",$tmp1,$tmp2),const_infor);
BUT What I want is the output should be :
Your Balance are: 100 USD; 1000 BAT; 2000 RIEL
How can I pass the $currency. to str_replace ?
Anyone can help me to do this.?

I don't know what exactly you wanna do but if it's only output
try
printf("Your Money %f %f %f", $money["USD"], $money["BAT"], $money["RIEL"]);

Well, below is just kind of a parser for doing what you want.. Try and see if it fits your needs:
function replace($string, $name = '', $value = '')
{
if ( !empty($name) )
{
str_replace('{'.$name.'}', $value, $string);
}
}
$string = 'Your balance is {bal1} USD, {bal2} BAT';
$string = replace('bal1', $money['USD'], $string);
$string = replace('bal2', $money['BAT'], $string);
$string = replace('bal3', $money['GBP'], $string);
print $string;

try that:
foreach ($money as $key => $cur)
echo $cur.' '. $key;

Related

check the same char in strg and remove and split from underscore in PHP?

Hello I have one string "22A_n22A" and i want to remove the same character from this string and want to split from "_" to two string like 22A and n22A.
i tried it but did not get any solution.
final out put i want like 22A_n22A to (n)22AA
<?php
function conti($str,$case_sensitive = false) {
//if($com1 = preg_replace("/\b(\w+)\s+\\1\b/i", "$1", $newval))
if(strcmp($case_sensitive , $case_sensitive) === 0 )
{
$pieces = explode("_", $str);
$str1 = $pieces[0];
$str2 = $pieces[1];
$ary1 = str_split($str1);
$ary2 = str_split($str2);
if (isset($case_sensitive))
{
$ary1 = array_map('strtolower',$ary1);
$ary2 = array_map('strtolower',$ary2);
}
$com = implode('',array_intersect($ary1,$ary2));
$diff = implode('',array_merge(array_diff($ary1, $ary2),array_diff($ary2, $ary1)));
$int = (int) filter_var($com, FILTER_SANITIZE_NUMBER_INT);
$onlystr = preg_replace('/\d/', '', $com);
$newval= '('.$diff.')'.$int.$onlystr.$onlystr;
// $com1 = preg_replace("/\b(\w+)\s+\\1\b/i", "$1", $str);
echo '<pre><h1>';
echo 'new value:';
print_r($newval);
echo "<br>";
echo "<br>";
echo "<br>";
echo 'new value:';
print_r($com);
echo "<br>";
echo 'new diff:';
print_r($diff);
echo '</pre>';
return $newval;
}
else {
echo '<pre><h1>';
echo 'oldvalue:';
print_r($str);
echo '</pre>';
return $str;
}
}
echo(conti('71A_n71A'));
// echo(conti('66A_n66A'));
?>
As stated in your comments your requirement is to:
Split the string on _
Pluck the last character from the first chunk of the string and append that to the end of the second string
Wrap the first character of the second chunk of the string in parentheses
For example, 65A_n66A becomes (n)66AA.
You can do this with by performing explode() on the original string, extracting the parts you need and piecing them back together in your desired format:
function format($string) {
list($first, $second) = explode('_', $string);
return sprintf('(%s)%s%s',
$second[0],
substr($second, 1),
$first[strlen($first) - 1]
);
}
This yields:
echo format('22A_n22A'); // (n)22AA
echo format('11A_n22B'); // (n)22BA
echo format('65A_n66A'); // (n)66AA
Hope this helps :)

Highlight multiple keywords advanced

I tried most of solution answered here but all of them have same problem which is my question here.
I use this function for highligh search results:
function highlightWords($searchtext, $searchstrings){
$searchstrings = preg_replace('/\s+/', ' ', trim($searchstrings));
$words = explode(' ', $searchstrings);
$highlighted = array();
foreach ( $words as $word ){
$highlighted[] = "<font color='#00f'><b>".$word."</b></font>";
}
return str_replace($words, $highlighted, $searchtext);
}
Problem occurs when i search text with 2 or more strings separated with spaces and any of them have any of HTML code from my highlighted array.
For example, searchtext="I have max system performance" AND searchstrings="max f"
In first iteration foreach will replace every max with <font color='#00f'><b>max</b></font>
In second iteration it will replace every f with <font color='#00f'><b>f</b></font>
Second iteration will also replace html tags inserted in first replacement!
So it will replace f in string <font color='#00f'> also?
Any suggestion?
Thanks
Miodrag
<?php
$searchtext = "I have max system performance";
$searchstrings = "max f";
$searchstrings = preg_replace('/\s+/', ' ', trim($searchstrings));
$words = explode(' ', $searchstrings);
$highlighted = array();
foreach ( $words as $word ){
$highlighted[] = "<font color='#00f'><b>".$word."</b></font>";
}
echo strtr($searchtext, array_combine($words, $highlighted));
?>
Maybe this is good Solution for you?
function highlightWords($searchtext, $searchstrings){
$searchstrings = preg_replace('/\s+/', ' ', trim($searchstrings));
$words = explode(' ', $searchstrings);
$highlighted = array();
foreach ( $words as $word ){
$highlighted[] = '<span class="highlighted-word">'.$word.'</span>';
}
return str_replace($words, $highlighted, $searchtext);
}
echo highlightWords('I have max system performance', 'max f');
?>
You need to add a little bit CSS on your Page:
<style>
.highlighted-word {
font-weight: bold;
}
</style>
Outputs:
I have max system performance
---
UPDATE:
If you like to hightlight the complete word, look at this:
function highlightCompleteWords($searchtext, $searchstrings){
$searchstrings = preg_replace('/\s+/', ' ', trim($searchstrings));
$words = explode(' ', $searchstrings);
$highlighted = array();
foreach ( $words as $word ){
$searchtext = preg_replace("/\w*?".preg_quote($word)."\w*/i", "<span class='highlighted-word'>$0</span>", $searchtext);
}
return $searchtext;
}
echo highlightCompleteWords('I have max system performance', 'max f');
Outputs: I have max system performance
I might not fully understand your question, but I guess you want to highlight every matched word in the search string.
You could probably just do something like:
$returnString = $searchtext;
foreach ( $words as $word ){
$returnString = preg_replace('/\b'.$word.'\b/i', "<font color='#00f'><b>$0</b></font>", $returnString);
}
return $returnString;
This would output: "I have max system performance"
Since the "f" wouldn't get matched
EDIT - This is if you wanna match part of a word as well.
Kind of ugly but I believe this will fork for you
$returnString = $searchtext;
foreach ( $words as $word ){
if(strlen($word)>2){
$returnString = preg_replace('/'.$word.'/i', "§§§$0###", $returnString);
}
}
$returnString = preg_replace("/\§§§/","<font color='#00f'><b>", $returnString);
$returnString = preg_replace("/\###/","</b></font>", $returnString);
return $returnString;
Try the following
foreach ( $words as $word ){
if(strlen ($word)>2)
{
$highlighted[] = "<font color='#00f'><b>".$word."</b></font>";
}
}

How to remove string with comma in a big string?

I'm a newbie in PHP ,andnow I'm struck on this problem . I have a string like this :
$string = "qwe,asd,zxc,rty,fgh,vbn";
Now I want when user click to "qwe" it will remove "qwe," in $string
Ex:$string = "asd,zxc,rty,fgh,vbn";
Or remove "fhg,"
Ex:$string = "asd,zxc,rty,vbn";
I try to user str_replace but it just remove the string and still have a comma before the string like this:
$string = ",asd,zxc,rty,fgh,vbn";
Anyone can help? Thanks for reading
Try this out:
$break=explode(",",$string);
$new_array=array();
foreach($break as $newData)
{
if($newData!='qwe')
{
$new_array[]=$newData;
}
}
$newWord=implode(",",$new_array);
echo $newWord;
In order to achieve your objective, array is your best friend.
$string = "qwe,asd,zxc,rty,fgh,vbn";
$ExplodedString = explode( "," , $string ); //Explode them separated by comma
$itemToRemove = "asd";
foreach($ExplodedString as $key => $value){ //loop along the array
if( $itemToRemove == $value ){ //check if item to be removed exists in the array
unset($ExplodedString[$key]); //unset or remove is found
}
}
$NewLook = array_values($ExplodedString); //Re-index the array key
print_r($NewLook); //print the array content
$NewLookCombined = implode( "," , $NewLook);
print_r($NewLookCombined); //print the array content after combined back
here the solution
$string = "qwe,asd,zxc,rty,fgh,vbn";
$clickword = "vbn";
$exp = explode(",", $string);
$imp = implode(" ", $exp);
if(stripos($imp, $clickword) !== false) {
$var = str_replace($clickword," ", $imp);
}
$str = preg_replace('/\s\s+/',' ', $var);
$newexp = explode(" ", trim($str));
$newimp = implode(",", $newexp);
echo $newimp;
You could try preg_replace http://uk3.php.net/manual/en/function.preg-replace.php if you have the module set up. It will allow you to optionally replace trailing or leading commas easily:
preg_replace("/,*$providedString,*/i", '', "qwe,asd,zxc,rty,fgh,vbn");

i want text and numeric part from the string in php

i have one string
$str ='california 94063';
now i want california and 94063 both in diferent variable.
string can be anything
Thanks in advance....
How about
$strings = explode(' ', $str);
Assuming that your string has ' ' as a separator.
Then, if you want to find the numeric entries of the $strings array, you can use is_numeric function.
Do like this
list($str1,$str2)=explode(' ',$str);
echo $str2;
If your string layout is always the same (say: follows a given format) then I'd use sscanf (http://www.php.net/manual/en/function.sscanf.php).
list($str, $number) = sscanf('california 94063, "%str %d");
<?php
$str ='california 94063';
$x = preg_match('(([a-zA-Z]*) ([0-9]*))',$str, $r);
echo 'String Part='. $r[1];
echo "<br />";
echo 'Number Part='.$r[2];
?>
If text pattern can be changed then I found this solution
Source ::
How to separate letters and digits from a string in php
<?php
$string="94063 california";
$chars = '';
$nums = '';
for ($index=0;$index<strlen($string);$index++) {
if(isNumber($string[$index]))
$nums .= $string[$index];
else
$chars .= $string[$index];
}
echo "Chars: -".trim($chars)."-<br>Nums: -".trim($nums)."-";
function isNumber($c) {
return preg_match('/[0-9]/', $c);
}
?>

Extract 2 sets of numbers from a string using PHP's preg?

Here's some PHP code:
$myText = 'ABC #12345 (2009) XYZ';
$myNum1 = null;
$myNum2 = null;
How do I add the first set of numbers from $myText after the # in to $myNum1 and the second numbers from $myText that are in between the () in to $myNum2. How would I do that?
preg_match('/#(\d+).*\((\d+)\)/', $myText, $matches);
$myNum1 = $matches[1];
$myNum2 = $matches[2];
assuming you have something like:
" stuff ... #123123 stuff (456456)"
that will give you
$myNum1 = 123123
$myNum2 = 456456
If you have an input string of form "123#456", you can do
$tempArray = explode("#", $input);
if (sizeof($tempArray) != 2) {
echo "OH NO! Something bad happened!";
}
$value1 = intval($tempArray[0]);
$value2 = intval($tempArray[1]);
echo "Result: " . ($value1 + $value2);

Categories