Replace multiple elements in one string [duplicate] - php

This question already has an answer here:
How do I use str_replace() with multiple parameters?
(1 answer)
Closed 8 years ago.
I have the following string: "English,French,German".
Replacing one element in this string is no problem, doing this:
#if (strpos($language,'English') !== false)<dd>{{{ $malestr = str_replace("English", "Eng.", $language)}}}</dd>#endif
Resulting in: "Eng.,French,German"
Now the problem is I want to replace all three elements and return only one string, but I don't know how to get to this. Can you help?
--
edit: thanks to Mahammad Alabed, found the solution in your link. This worked:
{{{$result = str_replace(
array('English', 'French', 'German'),
array('Eng.', 'Fr.', 'Ge.'),
$language
)}}}

$languages = array(
'English' => 'Eng.',
'French' => 'Fre.',
'German' => 'Ger.',
);
$malestr = str_replace(array_keys($languages), array_values($languages), $language);
This will replace all the terms you're looking for.

Related

PHP replace text inside specific text [duplicate]

This question already has answers here:
Parse Wordpress like Shortcode
(7 answers)
Closed 4 years ago.
I'm using str_replace to replace a simple shortcode which works fine:
$content = "[old_shortcode]";
$old_shortcode = "[old_shortcode]";
$new_shortcode = "[new_shortcode]";
echo str_replace($old_shortcode, $new_shortcode, $content);
However I want to also replace attributes inside the shortcode without affecting any text content, for example change this:
[old_shortcode old_option_1="Text Content" old_option_2="Text Content"]
To this:
[new_shortcode new_option_1="Text Content" new_option_2="Text Content"]
Much appreciated if anyone could advise on how to do this.
To clarify, this question is not about parsing a shortcode (as it has been marked as a duplicated), it's about replacing one shortcode with another which the duplicate question linked to does not answer.
Edit:
I figured it out myself, however it's probably not a very elagant solution if anyone wants to suggest something better?
$pattern1 = '#\[shortcode(.*)attribute1="([^"]*)"(.*)\]#i';
$replace1 = '[shortcode$1attribute1_new="$2"$3]';
$pattern2 = '#\[shortcode(.*)attribute2="([^"]*)"(.*)\]#i';
$replace2 = '[shortcode$1attribute2_new="$2"$3]';
$pattern3 = '#\[shortcode(.*)(.*?)\[/shortcode\]#i';
$replace3 = '[new_shortcode$1[/new_shortcode]';
$content = '[shortcode attribute2="yes" attribute1="whatever"]Test[/shortcode]';
echo preg_replace(array($pattern1,$pattern2,$pattern3), array($replace1,$replace2,$replace3), $content);
Use preg_replace() instead that select only part of string you want using regex.
$newContent = preg_replace("/[a-zA-Z]+(_[^\s]+)/", "new$1", $content);
Check result in demo

PHP: get parent node where child = 'value' [duplicate]

This question already has answers here:
SimpleXML: Selecting Elements Which Have A Certain Attribute Value
(2 answers)
Closed 7 years ago.
I have this xml file:
<friends>
<friend>
<name>xxx</name>
<pays>France</pays>
</friend>
<friend>
<name>yyy</name>
<country>France</country>
</friend>
<friend>
<name>zzz</name>
<country>USA</country>
</friend>
</friends>
To get my data, I am using this php code:
$xml = simplexml_load_file('friends.xml');
$friendsXML = $xml->friend;
Which works fine, but returns all of the friends.
Now I want to retrieve only friends who are from France:
country = 'france'.
Can anyone help me doing that?
I'd use XPath for things like this. Try:
$res = $xml->xpath('friend[country = "france"]');
echo $res[0];

CakePhp, how MySQL "Like" works as case insensitive search [duplicate]

This question already has answers here:
How can I search (case-insensitive) in a column using LIKE wildcard?
(16 answers)
Closed 8 years ago.
In CakePhp, how MySQL Like works as case insensitive search.
I have tried with following code but problem is also coming here.
If i am searching "Motel Park" then result is fine.
But when searching "motel park" no result is found.
In database Collation is latin1_swedish_ci
$where_condition = array('Ad.completed' => 1,
'Ad.address LIKE '=>'%'.$_REQUEST['address'].'%',
'Ad.status' =>$ad_status
);
$result = $this->Ad->find('all',array('conditions'=>$where_condition));
You can convert both the value to lowercase to use LIKE statement
$where_condition = array(
'Ad.completed' => 1,
'LOWER(Ad.address) LIKE '=>'%'.strtolower($this->request->data['address']).'%',
'Ad.status' =>$ad_status
);
$result = $this->Ad->find('all',array('conditions'=>$where_condition));
try using "COLLATE utf_general_ci" collation. refer this link.
but there is an easy solution , by converting all string in to lowercase. then check.
$request_address=strtolower($_REQUEST['address']);
$where_condition = "Ad.completed = 1 AND
LOWER(Ad.address) LIKE '%".$request_address."%' AND
Ad.status ='".$ad_status."'";
$result = $this->Ad->find('all',array('conditions'=>$where_condition));

Changing language variable in URL [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Replace values in a URI query string
I am using a language switcher in the navigation bar to switch between EN and DE, my url structure is like this:
http://www.mydomain.com/gallery.php?lang=de
http://www.mydomain.com/gallery-item.php?id=100&lang=de
The switch works well on all urls which don't have an id, but it doesn't work with the ids.
<?php
$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
<a href='.$url.'?lang=en">
<a href='.$url.'?lang=de">
?>
What is a good solution to check for $lang=xx or ?lang=xx and then add ?lang=xx or $lang=xx respectively?
$params = $_GET;
$params['lang'] = 'en';
printf('En', $url, http_build_query($params));
$params['lang'] = 'de';
printf('De', $url, http_build_query($params));
Or even very compact:
printf('De',
$url, http_build_query(array('lang' => 'de') + $_GET));
http://php.net/http_build_query

Convert country codes [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
There are several methods on country codes.
I have a list of codes with 3-characters, like on this page:
http://www.fina.org/H2O/index.php?option=com_content&view=category&id=93:asia&Itemid=638&layout=default
Is there a simple way to convert them to 2-characters? Like "PT" from "POR" for Portugal.
Standard for 2-characters - http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
Thanks.
There are some useful data files that you can get from http://country.io/data that'll help you:
http://country.io/iso3.json - a map of ISO2 to ISO3 country codes
http://country.io/names.json - a map of ISO2 country codes to country names
If you just want to go from 3 letter codes to 2 letter codes you can just flip the first map and use that. You could create a map that goes directly from 3 letter codes to country names by combing the files though. Here's a simple PHP example:
$codes = json_decode(file_get_contents('http://country.io/iso3.json'), true);
$names = json_decode(file_get_contents('http://country.io/names.json'), true);
$iso3_to_name = array();
foreach($codes as $iso2 => $iso3) {
$iso3_to_name[$iso3] = $names[$iso2];
}
echo $names("PL"); // => "Poland"
echo $iso3_to_map("POL"); // => "Poland"
I see that the question was asked seven years ago. Today I had the similar issue and found one good solution. Hope that this answer will be helpful to others who will have the same issue in the future.
There is a separate library which can be used https://github.com/thephpleague/iso3166
Then the solution would be straightforward. $alpha3 is the three char representation of a country. And alpha2 is two char representation of the country.
$ composer require league/iso3166
$data = (new League\ISO3166\ISO3166)->alpha3($alpha3);
Data looks as follows:
[
'name' => 'Netherlands',
'alpha2' => 'NL',
'alpha3' => 'NLD',
'numeric' => '528',
'currency' => [
'EUR',
]
]
$countryCodeInTwoChar = $data['alpha2']
Without doing an actual lookup, there is no simple way: AFG (Afghanistan) becomes AF, while AND (Andorra) becomes AD, and BLR (Belarus) becomes BY... so you can't do any simple character manipulation to convert.
My suggestion would be to use a countrycode table, or add an extra column to any existing table, so that you hold both codes.
Most of the other answers above are not direct answers. Let me try
I have tried below code to convert 3-characters to 2-characters country code using API:
<?php
$list=["BWA","SLV","TZA","BRB","IND","BES","ANT"];
$iso3=file_get_contents('http://country.io/iso3.json');//load the country codes
$iso3=json_decode($iso3,true);//convert json to associative array
foreach($list as $k)
{
if($k=="ANT")//not defined in code list
echo "AN";
else
echo array_search($k,$iso3);
echo "<br/>";
}
?>
The country codes provided is in form of 2-iso(key):3-iso(value). So instead of searching for key, i searched by value and return the first corresponding key if successful.
Output
BW
SV
TZ
BB
IN
BQ
AN
Cons -
ANT country code is not defined in code list.
Reference - array_search
Building on the other info here, here's a complete function ready to go:
function convertCountryAlphas3To2($code='') {
$countries = json_decode('{"AFG":"AF","ALA":"AX","ALB":"AL","DZA":"DZ","ASM":"AS","AND":"AD","AGO":"AO","AIA":"AI","ATA":"AQ","ATG":"AG","ARG":"AR","ARM":"AM","ABW":"AW","AUS":"AU","AUT":"AT","AZE":"AZ","BHS":"BS","BHR":"BH","BGD":"BD","BRB":"BB","BLR":"BY","BEL":"BE","BLZ":"BZ","BEN":"BJ","BMU":"BM","BTN":"BT","BOL":"BO","BIH":"BA","BWA":"BW","BVT":"BV","BRA":"BR","VGB":"VG","IOT":"IO","BRN":"BN","BGR":"BG","BFA":"BF","BDI":"BI","KHM":"KH","CMR":"CM","CAN":"CA","CPV":"CV","CYM":"KY","CAF":"CF","TCD":"TD","CHL":"CL","CHN":"CN","HKG":"HK","MAC":"MO","CXR":"CX","CCK":"CC","COL":"CO","COM":"KM","COG":"CG","COD":"CD","COK":"CK","CRI":"CR","CIV":"CI","HRV":"HR","CUB":"CU","CYP":"CY","CZE":"CZ","DNK":"DK","DKK":"DK","DJI":"DJ","DMA":"DM","DOM":"DO","ECU":"EC","Sal":"El","GNQ":"GQ","ERI":"ER","EST":"EE","ETH":"ET","FLK":"FK","FRO":"FO","FJI":"FJ","FIN":"FI","FRA":"FR","GUF":"GF","PYF":"PF","ATF":"TF","GAB":"GA","GMB":"GM","GEO":"GE","DEU":"DE","GHA":"GH","GIB":"GI","GRC":"GR","GRL":"GL","GRD":"GD","GLP":"GP","GUM":"GU","GTM":"GT","GGY":"GG","GIN":"GN","GNB":"GW","GUY":"GY","HTI":"HT","HMD":"HM","VAT":"VA","HND":"HN","HUN":"HU","ISL":"IS","IND":"IN","IDN":"ID","IRN":"IR","IRQ":"IQ","IRL":"IE","IMN":"IM","ISR":"IL","ITA":"IT","JAM":"JM","JPN":"JP","JEY":"JE","JOR":"JO","KAZ":"KZ","KEN":"KE","KIR":"KI","PRK":"KP","KOR":"KR","KWT":"KW","KGZ":"KG","LAO":"LA","LVA":"LV","LBN":"LB","LSO":"LS","LBR":"LR","LBY":"LY","LIE":"LI","LTU":"LT","LUX":"LU","MKD":"MK","MDG":"MG","MWI":"MW","MYS":"MY","MDV":"MV","MLI":"ML","MLT":"MT","MHL":"MH","MTQ":"MQ","MRT":"MR","MUS":"MU","MYT":"YT","MEX":"MX","FSM":"FM","MDA":"MD","MCO":"MC","MNG":"MN","MNE":"ME","MSR":"MS","MAR":"MA","MOZ":"MZ","MMR":"MM","NAM":"NA","NRU":"NR","NPL":"NP","NLD":"NL","ANT":"AN","NCL":"NC","NZL":"NZ","NIC":"NI","NER":"NE","NGA":"NG","NIU":"NU","NFK":"NF","MNP":"MP","NOR":"NO","OMN":"OM","PAK":"PK","PLW":"PW","PSE":"PS","PAN":"PA","PNG":"PG","PRY":"PY","PER":"PE","PHL":"PH","PCN":"PN","POL":"PL","PRT":"PT","PRI":"PR","QAT":"QA","REU":"RE","ROU":"RO","RUS":"RU","RWA":"RW","BLM":"BL","SHN":"SH","KNA":"KN","LCA":"LC","MAF":"MF","SPM":"PM","VCT":"VC","WSM":"WS","SMR":"SM","STP":"ST","SAU":"SA","SEN":"SN","SRB":"RS","SYC":"SC","SLE":"SL","SGP":"SG","SVK":"SK","SVN":"SI","SLB":"SB","SOM":"SO","ZAF":"ZA","SGS":"GS","SSD":"SS","ESP":"ES","LKA":"LK","SDN":"SD","SUR":"SR","SJM":"SJ","SWZ":"SZ","SWE":"SE","CHE":"CH","SYR":"SY","TWN":"TW","TJK":"TJ","TZA":"TZ","THA":"TH","TLS":"TL","TGO":"TG","TKL":"TK","TON":"TO","TTO":"TT","TUN":"TN","TUR":"TR","TKM":"TM","TCA":"TC","TUV":"TV","UGA":"UG","UKR":"UA","ARE":"AE","GBR":"GB","USA":"US","UMI":"UM","URY":"UY","UZB":"UZ","VUT":"VU","VEN":"VE","VNM":"VN","VIR":"VI","WLF":"WF","ESH":"EH","YEM":"YE","ZMB":"ZM","ZWE":"ZW","GBP":"GB","RUB":"RU","NOK":"NO"}',true);
$out = $countries[$code];
return $out;
}
While this may be a lengthy and painful method, it may very well be worth your while writing a function that you can keep forever more, maybe this can point you in the right direction:
<?php
function myCodes($in, $type){
$out = "";
$long = array('portugal', 'united kingdom');
$short = array('pt', 'uk');
$in = strtolower(trim($in));
switch($type){
case 'long':$out = str_replace($short, $long, $in);break;
case 'short':$out = str_replace($long, $short, $in);break;
}
echo $out;
}
echo myCodes('United Kingdom', 'short'); //this will echo 'uk'
echo myCodes('UK', 'long'); //this will echo 'united kingdom'
?>
This will of course have a few drawbacks such as making sure that the arrays for long and short match up position wise, and you'll need to maintain the function as well.
$mapping['POR'] = 'PT';
$shortcode = $mapping[$longcode];
In ruby you can get this done like this:
(get countryInfo.txt from http://download.geonames.org/export/dump/ )
require 'csv'
countries_iso3_map = {}
CSV.foreach('countryInfo.txt',:col_sep=>' ',:row_sep =>:auto) do |row|
next if row[0][0] == '#' #ignore comments section
countries_iso3_map[row[0][0,2]]= row[1][0,3]
end
p countries_iso3_map['PT']
There is going to be no easy way because there is no particular scheme in the names of the country. For example PT from POR for Portugal and this can be different for other countries as well. You might want to create an array to hold two letters for each country.
Example:
$countries = array('PT' => 'Portugal', 'UK' => 'United Kingdom');

Categories