I have an associative array of links like this
$my_links = [
'city 1' => 'http://link1',
'city 2' => 'http://link2',
'Head Office' => 'http://link3'
];
and some html like this. The html is dynamically generated by a script ( wordpress blog content).
<p>
You can visit our stores at City 1
and City 2,
or visit our Head office.
</p>
Required Output: Make clickable links using indices of above array
<p>
You can visit our stores at City 1
and City 2,
or visit our Head office.
</p>
How to achieve this using PHP and/or JQuery?
<?php
$my_links = [
'city 1' => 'http://link1',
'city 2' => 'http://link2',
'Head Office' => 'http://link3'
];
$str = "<p>
You can visit our stores at City 1
and City 2,
or visit our Head office.
</p>";
foreach ($my_links as $link_title => $link) {
$str = str_ireplace($link_title,"<a href='$link'>".ucwords($link_title)."</a>",$str);
}
echo $str;
Loop over your $my_links. Find the link title present in the string and use str_ireplace() to replace the link title with the anchor tags.
Just use the array references:
<p>
You can visit our stores at City 1
and City 2,
or visit our Head office.
</p>
If your content is coming from PHP, use PHP's str_replace() function.
This function's three parameters search the purpose:
search: string or array
replace: string or array
actual string: string
If search and replace are arrays, their elements count should be same.
Now, find the string segments like City 1, City 2 and Head Office and replace them by adding <a href="... to them.
Code:
<?php
$my_links = [
'city 1' => 'http://link1',
'city 2' => 'http://link2',
'Head Office' => 'http://link3'
];
$content = '<p>
You can visit our stores at City 1
and City 2,
or visit our Head office.
</p>';
$find = ['City 1', 'City 2', 'Head office'];
$replace = [
'City 1',
'City 2',
'Head Office',
];
echo str_replace($find, $replace, $content);
?>
A Quick Update:
Please use str_ireplace() instead of str_replace() discussed above as we have case insensitive comparison e.g. city 1 vs City 1. This function works the same way as str_replace(), only it is case insensitive.
You can try this
<p>
You can visit our stores at City 1
and City 2,
or visit our Head office.
</p>
Related
I need to parse a street address in PHP a string that might have abbreviations.
This string comes from a text input.
The fields I need to search are:
street (alphanumeric - might have
building (alphanumeric - might have
number (alphanumeric - might have
area (numeric from 1 to 5)
other (unknown field & used to search in all the above fields in the database)
For example users submits one of this text text:
street Main Road Bulding H7 Number 5 Area 1
st Main Road bldg H7 Nr 5 Ar 5
stMain bldgh7
ar5 unknown other search parameter
street Main Road h7 2b
street main street str main road
The outcome I would like to see as a array:
[street]=>Main Road [building]=>h7 [number]=>5 [area]=>1
[street]=>Main Road [building]=>h7 [number]=>5 [area]=>5
[street]=>Main [building]=>h7
[area]=>5 [other]=>unknown other search parameter
[street]=>Main Road [other]=>h7 2b
[street]=>Main Street&&Main Road
My code so far...but dosen't work with examples 3.,4.,5.,6.:
<?php
//posted address
$address = "str main one bldg 5b other param area 1";
//to replace
$replace = ['street'=>['st','str'],
'building'=>['bldg','bld'],
'number'=>['nr','numb','nmbr']];
//replace
foreach($replace as $field=>$abbrs)
foreach($abbrs as $abbr)
$address = str_replace($abbr.' ',$field.' ',$address);
//fields
$fields = array_keys($replace);
//match
if(preg_match_all('/('.implode('|',array_keys($fields)).')\s+([^\s]+)/si', $address, $matches)) {
//matches
$search = array_combine($matches[1], $matches[2]);
//other
$search['other'] = str_replace($matches[0],"",$address);
}else{
//search in all the fields
$search['other'] = $address;
}
//search
print_r($search);
Code tester: http://ideone.com/j3q4YI
Wow, you've got one hairy mess to clean up. I've toiled for a few hours on this. It works on all of your samples, but I would NOT stake my career on it being perfect on all future cases. There are simply too many variations in addresses. I hope you can understand my process and modify it if/when new samples failed to be captured properly. I'll leave all my debugging comment in place, because I reckon you'll use them for future edits.
$addresses=array(
"street Main Road Bulding H7 Number 5 Area 1",
"st Main Road bldg H7 Nr 5 Ar 5",
"stMain bldgh7",
"ar5 unknown other search parameter",
"street Main Road h7 2b",
"street main street str main road"
);
$regex["area"]="/^(.*?)(ar(?:ea)?\s?)([1-5])(.*?)$/i";
$regex["number"]="/^(.*?)(n(?:umbe)?r\s?)([0-9]+)(.*?)$/i";
$regex["building"]="/^(.*?)(bu?i?ldi?n?g\s?)([^\s]+)(.*?)$/i";
$regex["corner"]="/^(.*?str?(?:eet)?)\s?(str?(?:eet)?.*)$/i"; // 2 streets in string
$regex["street"]="/^(.*?)(str?(?:eet)?\s?)([^\s]*(?:\s?ro?a?d|\s?str?e?e?t?|.*?))(\s?.*?)$/i";
$regex["other"]="/^(.+)$/";
$search=[];
foreach($addresses as $i=>$address){
echo "<br><div><b>$address</b> breakdown:</div>";
foreach($regex as $key=>$rgx){
if(strlen($address)>0){
//echo "<div>addr(",strlen($address),") $address</div>";
if(preg_match($rgx,$address,$matches)){
if($key=="other"){
$search[$i][$key]=$matches[0]; // everything that remains
}elseif($key=="corner"){
$search[$i]["street"]=""; // NOTICE suppression
// loop through both halves of corner address omitting element[0]
foreach(array_diff_key($matches,array('')) as $half){
//echo "half= $half<br>";
if(preg_match($regex["street"],$half,$half_matches)){
//print_r($half_matches);
$search[$i]["street"].=(strlen($search[$i]["street"])>0?"&&":"").ucwords($half_matches[3]);
$address=trim($half_matches[1].$half_matches[4]);
// $matches[2] is the discarded identifier
//echo "<div>$key Found: {$search[$i][$key]}</div>";
//echo "<div>Remaining: $address</div>";
}
}
}else{
$search[$i][$key]=($key=="street"?ucwords($matches[3]):$matches[3]);
$address=trim($matches[1].$matches[4]);
// $matches[2] is the discarded identifier
//echo "<div>$key Found: {$search[$i][$key]}</div>";
//echo "<div>Remaining: $address</div>";
//print_r($matches);
}
}
}else{
break; // address is fully processed
}
}
echo "<pre>";
var_export($search[$i]);
echo "</pre>";
}
The output is an array that satisfies your brief, but the keys are out of order because I captured the address components out of order -- this may not matter to you, so I didn't bother re-sorting it.
street Main Road Bulding H7 Number 5 Area 1 breakdown:
array (
'area' => '1',
'number' => '5',
'building' => 'H7',
'street' => 'Main Road',
)
st Main Road bldg H7 Nr 5 Ar 5 breakdown:
array (
'area' => '5',
'number' => '5',
'building' => 'H7',
'street' => 'Main Road',
)
stMain bldgh7 breakdown:
array (
'building' => 'h7',
'street' => 'Main',
)
ar5 unknown other search parameter breakdown:
array (
'area' => '5',
'other' => 'unknown other search parameter',
)
street Main Road h7 2b breakdown:
array (
'street' => 'Main Road',
'other' => 'h7 2b',
)
street main street str main road breakdown:
array (
'street' => 'Main Street&&Main Road',
)
...boy am I glad this project doesn't belong to me. Good luck!
Thank you for the help! I thought that I should do something like multiple preg_matches.
I just found a PHP extension that does exactly what I want.
The library is PHP Postal (https://github.com/openvenues/php-postal) and requires libpostal. It takes about 15-20 seconds to load the library when you run PHP, after this everything work ok.
Total execution time for parsing: 0.00030-0.00060 seconds.
$parsed = Postal\Parser::parse_address("The Book Club 100-106 Leonard St, Shoreditch, London, Greater London, EC2A 4RH, United Kingdom");
foreach ($parsed as $component) {
echo "{$component['label']}: {$component['value']}\n";
}
Output:
house: the book club
house_number: 100-106
road: leonard st
suburb: shoreditch
city: london
state_district: greater london
postcode: ec2a 4rh
country: united kingdom
All I had to do after this is to replace my labels and format the address.
Hope this will help others, who want to parse a address in PHP.
I've been trying to figure out how to separate these items.. I'm getting a full array like this:
array = ('name' => 'test', 'last name' => 'test' , 'name' => 'test1');
But i need it this way: (Example not well typed)
0[('name' => 'a name', 'lastname' => 'a last name')], 1[('name' => 'a name', 'last name' => 'a last name')]
I only need to find one string and the last name behind that string. I can't transform the array because it's from a real big XML file.
thanks for your help guys.
I've found a real easy solution. Stupid of me!
$array = array($items['name'] => $items['last_name']);
Need some help with parsing a text file into PHP. The file is generated by a PHP script, so I don't have control over the content formatting. The text file looks like this:
7/4/2013-7/4/2013 Best Legs in a Kilt To start the summer
off with a bang, the Playhouse has teamed up with the folks at The
Festival. kilt.jpg 1,1,0,
-
7/8/2013-7/23/2013 Hot Legs Yes, folks, it's all platform
shoes, leisure suits, and crazy hair-do's. hotstuff.jpg
1,1,0,
-
The code that I have thus far is:
$content = file_get_contents('DC_PictureCalendar/admin/database/cal2data.txt');
list($date, $showname, $summary, $image, $notneeded, $notneeded2) = explode("\n", $content);
echo 'Show Name' . $showname . '<br/>';
This only gets me the first show title, I need to grab all of them. I'm sure a For loop would do it, but not sure how to do it based on the contents of the file. All I need is the 2nd line (show title) and the 4th line (image). Any help? Thanks in advance.
If you are reading the entire file into an array anyway, then just use file() which will read each line into an array.
$content = file('DC_PictureCalendar/admin/database/cal2data.txt', FILE_IGNORE_NEW_LINES);
You can then filter all the lines you don't want like this
$content = array_diff($content, array('1,1,0', '-'));
You can then break into chunks of 4 lines each (i.e. one item per entry)
$content_chunked = array_chunk($content, 4);
This would give you an array like
Array(
0 => Array(
0 => '7/4/2013-7/4/2013',
1 => 'Best Legs in a Kilt',
2 => 'To start the summer off with a bang, the Playhouse has teamed up with the folks at The Festival.',
3 => 'kilt.jpg'
),
1 => Array(
0 => '7/8/2013-7/23/2013',
1 => 'Hot Legs',
2 => 'Yes, folks, it's all platform shoes, leisure suits, and crazy hair-do's.',
3 => 'hotstuff.jpg'
) ... etc.
)
I would then map this array into a useful array of objects with property names that are meaningful to you:
$items = array_map(function($array)) {
$item = new StdClass;
$item->date = $array[0];
$item->showname = $array[1];
$item->summary = $array[2];
$item->image = $array[3];
return $item;
}, $content_chunked);
That would leave you with an array of objects like:
Array(
0 => stdClass(
'date' => '7/4/2013-7/4/2013',
'showname' => 'Best Legs in a Kilt',
'summary' => 'To start the summer off with a bang, the Playhouse has teamed up with the folks at The Festival.',
'image' => 'kilt.jpg'
),
1 => stdClass(
'date' => '7/8/2013-7/23/2013',
'showname' => 'Hot Legs',
'summary' => 'Yes, folks, it's all platform shoes, leisure suits, and crazy hair-do's.',
'image' => 'hotstuff.jpg'
) ... etc.
)
Hey how could I save array into multiple row in database please? I am using mysql database with php.
// GETTING ALL THE B NODE STUFFS AND PRINTING IT'S CONTENTS
$result = array();
foreach($document->getElementsByTagName('b') as $node){
$result[preg_replace('/:\s+$/','',$node->textContent)] = trim($node->nextSibling->textContent);
}
var_dump($result);
Here is the result am pulling from my array.
array
'Choose by Subject Category or Module Code' => string '' (length=0)
'
Back to Home page' => string '' (length=0)
'International' => string 'visiting students should consult the' (length=36)
'Undergraduate' => string 'students should refer to the relevant section of the UCC' (length=56)
'Postgraduate' => string 'students should refer to the relevant section of the UCC' (length=56)
'Credit Weighting' => string '5' (length=1)
'Teaching Period(s)' => string 'Teaching Period 1.' (length=18)
'No. of Students' => string 'Min 15, Max 30.' (length=15)
'Pre-requisite(s)' => string 'None' (length=4)
'Co-requisite(s)' => string 'None' (length=4)
'Teaching Methods' => string '1 x 4hr(s) Lectures; Other (Distance Education Module - Up to 146hrs Self Directed Study).' (length=90)
'Module Co-ordinator' => string 'Dr Peter Cleary, Department of Accounting, Finance and Information Systems.' (length=75)
'Lecturer(s)' => string 'Staff, Department of Accounting, Finance and Information Systems.' (length=65)
'Module Objective' => string 'To examine the management uses of accounting information and to enhance students ability to exert effective managerial control.' (length=127)
'Module Content' => string 'Topics include; the accounting information needs of management, costs and pricing; estimating costs; the identification of key performance indicators; budgeting for control; capital investment appraisal and implications for strategic planning and control.' (length=256)
'Learning Outcomes' => string 'On successful completion of this module, students should be able to:' (length=68)
'Assessment' => string 'Total Marks 100: Continuous Assessment 100 marks (Project/ Essay. Approximately 1500 words.).' (length=93)
'Compulsory Elements' => string 'Continuous Assessment.' (length=22)
'Penalties (for late submission of Course/Project Work etc.)' => string 'Where work is submitted up to and including 7 days late, 10% of the total marks available shall be deducted from the mark achieved. Where work is submitted up to and including 14 days late, 20% of the total marks available shall be deducted from the mark achieved. Work submitted 15 days late or more shall be assigned a mark of zero.' (length=336)
'Pass Standard and any Special Requirements for Passing Module' => string '40%.' (length=4)
'End of Year Written Examination Profile' => string 'No End of Year Written Examination.' (length=35)
'Requirements for Supplemental Examination' => string 'Marks in passed element(s) of Continuous Assessment are carried forward, Failed element(s) of Continuous Assessment must be repeated (Resubmission of revised Continuous Assessment).' (length=181)
I did try a for each statement with NSERT query inside but all the content was saved in a colum instead.
$array_data = implode("array_separator", $result);
foreach($result as $snode){
$query = sprintf("INSERT INTO save_array (ModuleCode) VALUES ('%s')",mysql_real_escape_string($snode));
mysql_query($query) or die('Error, insert query failed');
echo $snode.<br />';
}
echo '<br /><br /><br />';
Any help would be appreciated. Thanks.
//============== LATEST INSERT QUERY================//
$array_data = implode("array_separator", $result);
foreach($result as $snode){
$query = sprintf("INSERT INTO save_array
(ModuleCode,
Homepage,
International,
Undergraduate,
Postgraduate,
CreditWeighting,
TeachingPeriod,
NoofStudents,
Prerequisite,
Corequisite,
TeachingMethods,
ModuleCoordinator,
Lecturer,
ModuleObjective,
ModuleContent,
LearningOutcomes,
Assessment,
CompulsoryElements,
Penalties,
PassStandard,
EndofYearWrittenExamination,
RequirementsforExamination) VALUES ('%s')",mysql_real_escape_string($snode));
foreach ($result as $key => $value)
$query = $query . "$value";
echo '<br /><br />';
mysql_query($query) or die($query."<br/><br/>".mysql_error());
echo $snode. '<br />';
}
echo '<br /><br /><br />';
You can loop on all elements of array and prepare SQL INSERT INTO statment, and when you do this execute it.
A quick answer would be to iterate through a foreach loop, concatenating the values into an INSERT query (for more information, see http://dev.mysql.com/doc/refman/5.5/en/insert.html), and have the foreach loop exclude the keys "Undergraduate", "International", and "Postdoc", as well as any values that have length 0.
Your problem seems to be in the INSERT query. Try something like this:
$query = sprintf("INSERT INTO save_array (CreditWeighting, TeachingPeriod, NoofStudents, etc.)) VALUES ('%s')",mysql_real_escape_string($snode));
foreach ($result as $key => $value)
$query = $query . "$value";
And do some tweaking to get the query string just right.
My config.php contains:
$a1="title";
$b1="text";
$a2="title2";
$b2="text2";
and I have 1.php which includes config.php.
I need to include ($a1 and $b1) or ($a and $b) randomly.
How can I do this? :)
Thank you.
If this data is related, and you need a random set, store it in an array:
$sets = array(
array(
'title' => 'Some title',
'text' => 'Some text here about the title'
),
array(
'title' => 'Some other title',
'text' => 'Some other text here about the title'
)
);
With this array, we have two indexes that we can choose from:
$sets[0]; // Title: Some title, Text: Some text here about the title
$sets[1]; // Title: Some other title, Text: Some other text here about the title
If we want one of those, randomly, we could do the following:
$index = array_rand( $sets, 1 );
This will select either 0, or 1. With more entries in our array, the potential for this number to be larger also increases. We can then use it to grab one of our sets of data:
$dataSet = $sets[ $index ];
And then display the output:
echo $dataSet['title'];
echo $dataSet['text'];