Keyword matching in an array/string of keywords using PHP - php

I have a piece of PHP code as follows:
$words = array(
'Artist' => '1',
'Tony' => '2',
'Scarface' => '3',
'Omar' => '4',
'Frank' => '5',
'Torrentino' => '6',
'Mel Gibson' => '7',
'Frank Sinatra' => '8',
'Shakes' => '9',
'William Shakespeare' => '10'
);
$text = "William Shakespeare is very famous in the world. An artist is a person engaged in one or more of any of a broad spectrum of activities related to creating art, practicing the arts, and/or demonstrating an art. Artist is a descriptive term applied to a person who engages in an activity deemed to be an art. Frank Sinatra was an American singer, actor, director, film producer, and conductor. Frank Sinatra was born on December 12, 1915, in Hoboken, New Jersey, the only child of Italian immigrants Natalina Garaventa and Antonino Martino Sinatra, and was raised Roman Catholic.";
$re = '/\b(?:' . join('|', array_map(function($keyword) {
return preg_quote($keyword, '/');
}, array_keys($words))) . ')\b/i';
preg_match_all($re, $text, $matches);
foreach ($matches[0] as $keyword) {
echo $keyword, " ", $words[$keyword], "\n";
}
The code returns the below:
William Shakespeare 10 artist Artist 1 Frank 5 Frank 5
The code works well to not echo the partial keywords such as 'Shakes' => '9' in Shakespeare. However, as you can see the code can not detect 'Frank Sinatra' => '8' as a keyword as it is in Frank Sinatra was an American singer, also artist does not have any value (i.e. 1). Could you please help me to change the code somehow to echo William Shakespeare 10 artist 1 Artist 1 Frank 5 Frank 5 Frank Sinatra 8 Frank Sinatra 8 instead of William Shakespeare 10 artist Artist 1 Frank 5 Frank 5 in the current version. thanks for your help.

I've managed to achieve result:
William Shakespeare 10 artist 1 Artist 1 Frank Sinatra 8 Frank Sinatra
8
using the code:
<?php
mb_internal_encoding('UTF-8');
$words = array(
'Artist' => '1',
'Tony' => '2',
'Scarface' => '3',
'Omar' => '4',
'Frank' => '5',
'Torrentino' => '6',
'Mel Gibson' => '7',
'Frank Sinatra' => '8',
'Shakes' => '9',
'William Shakespeare' => '10'
);
uksort($words, function ($a, $b) {
$as = mb_strlen($a);
$bs = mb_strlen($b);
if ($as > $bs) {
return -1;
}
else if ($bs > $as) {
return 1;
}
return 0;
});
$words_ci = array();
foreach ($words as $k => $v) {
$words_ci[mb_strtolower($k)] = $v;
}
$text = "William Shakespeare is very famous in the world. An artist is a person engaged in one or more of any of a broad spectrum of activities related to creating art, practicing the arts, and/or demonstrating an art. Artist is a descriptive term applied to a person who engages in an activity deemed to be an art. Frank Sinatra was an American singer, actor, director, film producer, and conductor. Frank Sinatra was born on December 12, 1915, in Hoboken, New Jersey, the only child of Italian immigrants Natalina Garaventa and Antonino Martino Sinatra, and was raised Roman Catholic.";
$re = '/\b(?:' . join('|', array_map(function($keyword) {
return preg_quote($keyword, '/');
}, array_keys($words))) . ')\b/i';
preg_match_all($re, $text, $matches);
foreach ($matches[0] as $keyword) {
echo $keyword, " ", $words_ci[mb_strtolower($keyword)], "\n";
}

Related

PHP parse street address with abbreviations from text input for search

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.

replicate d3 indented tree to ms word using phpdocx

http://bl.ocks.org/mbostock/1093025
Hi, we can used to above link for reference as you can see it is an indented tree in d3. What i want to do is to replicate that tree in ms word using phpdocx. Here is what i have tried so far. I'm using a text with a border to replicate the rectangle in d3 and a line. I want my LINE at the back of my TEXT so that i can replicate the d3 indented tree. I used the position: absolute and z-index in the line but stil i have problem layouting my TEXT AND LINE to phpdocx i wish i can an image of what i have so far i dont have enough privelege to do so
below code is what i have so far
<?php
require_once 'classes/CreateDocx.inc';
$docx = new CreateDocx();
$array = array('young girl rape our young girls but violeta gave willingly gosh shes nervous','young girl rape our young girls but violeta gave willingly gosh shes nervous','young girl rape our young girls but violeta gave willingly gosh shes nervous','young girl rape our young girls but violeta gave willingly gosh shes nervous');
$a = ($k * 10) + 10;
$b = ($k * 10) + 60;
$options = array('points' => "$a,$a $a,$b $b,$b",
'strokecolor' => '#ff00ff',
'strokeweight' => '2',
'position' => 'absolute',
'fillcolor' => 'none',
'z-index' => -500
);
$docx->addShape('polyline', $options);
foreach($array as $k => $v){
$indentLeft = $k * 250;
$paragraphOptions = array( 'border' => 'single',
'position' => 'absolute',
'borderColor' => 'b70000',
'borderWidth' => 12,
'backgroundColor' => '#F4F4F4',
'indentLeft' => $indentLeft,
'spacingBottom' => 50,
'fontSize' => 10,
);
$docx->addText($v, $paragraphOptions);
}
$docx->createDocx('example_addTextBox_1');
?>

Bibtex php preg_match_all

I have a text file with a Bibtex export.
The text file has a number of entries following the pattern below.
#article{ls_leimeister,
added-at = {2013-01-18T11:14:11.000+0100},
author = {Wegener, R. and Leimeister, J. M.},
biburl = {http://www.bibsonomy.org/bibtex/27bb26b4b4858439f81aa0ec777944ac5/ls_leimeister},
journal = {International Journal of Technology Enhanced Learning (to appear)},
keywords = {Challenges Communities: Factors Learning Success VirtualCommunity and itegpub pub_jml pub_rwe},
note = {JML_390},
title = {Virtual Learning Communities: Success Factors and Challenges},
year = 2013
}
I want to use php and considered preg_match_all
The following didnt get me anywhere:
preg_match_all('/#^.*}$/', file_get_contents($file_path),$results);
I wanted to start simple, but that didnt really work.
I am kinda new to php RegEx.
The perfect final output would be:
Array
(
[0] => Array
(
['type'] => article
['unique_name'] => ls_leimeister
['added-at'] => 2013-01-18T11:14:11.000+0100
['author'] => Wegener, R. and Leimeister, J. M.
['biburl'] => http://www.bibsonomy.org/bibtex/27bb26b4b4858439f81aa0ec777944ac5/ls_leimeister
['journal'] => International Journal of Technology Enhanced Learning (to appear)
['keywords'] => Challenges Communities: Factors Learning Success VirtualCommunity and itegpub pub_jml pub_rwe
['note'] => JML_390
['title'] => Virtual Learning Communities: Success Factors and Challenges
['year'] => 2013
)
[1] => Array
(
[...] => …
)
)
Try this : Here I have fetched only type and unique_name, by looking at it, you can fetch all others.
$str = '#article{ls_leimeister,
added-at = {2013-01-18T11:14:11.000+0100},
author = {Wegener, R. and Leimeister, J. M.},
biburl = {http://www.bibsonomy.org/bibtex/27bb26b4b4858439f81aa0ec777944ac5/ls_leimeister},
journal = {International Journal of Technology Enhanced Learning (to appear)},
keywords = {Challenges Communities: Factors Learning Success VirtualCommunity and itegpub pub_jml pub_rwe},
note = {JML_390},
title = {Virtual Learning Communities: Success Factors and Challenges},
year = 2013
}';
preg_match_all('/#(?P<type>\w+){(?P<unique_name>\w+),(.*)/',$str,$matches);
echo $matches['type'][0];
echo "<br>";
echo $matches['unique_name'][0];
echo "<br>";
echo "<pre>";
print_r($matches);
Output array format will be little different from yours, but you can change this format to yours.
Pattern: /^#([^{]+)\{([^,]+),\s*$|^\s*([^\R#=]+) = \{(.*?)}/ms (Demo)
This pattern has two alternatives; each containing two capture groups.
type and unique_name are captured and stored in elements [1] and [2].
all other key-value pairs are stored in elements [3] and [4].
This separated array storage allows reliable processing when constructing the desired output array structure.
Input:
$bibtex='#BOOK{ko,
title = {Wissenschaftlich schreiben leicht gemacht},
publisher = {Haupt},
year = {2011},
author = {Kornmeier, M.},
number = {3154},
series = {UTB},
address = {Bern},
edition = {4},
subtitle = {für Bachelor, Master und Dissertation}
}
#BOOK{nial,
title = {Wissenschaftliche Arbeiten schreiben mit Word 2010},
publisher = {Addison Wesley},
year = {2011},
author = {Nicol, N. and Albrecht, R.},
address = {München},
edition = {7}
}
#ARTICLE{shome,
author = {Scholz, S. and Menzl, S.},
title = {Alle Wege führen nach Rom},
journal = {Medizin Produkte Journal},
year = {2011},
volume = {18},
pages = {243-254},
subtitle = {ein Vergleich der regulatorischen Anforderungen und Medizinprodukte
in Europa und den USA},
issue = {4}
}
#INBOOK{shu,
author = {Schulz, C.},
title = {Corporate Finance für den Mittelstand},
booktitle = {Praxishandbuch Firmenkundengeschäft},
year = {2010},
editor = {Hilse, J. and Netzel, W and Simmert, D.B.},
booksubtitle = {Geschäftsfelder Risikomanagement Marketing},
publisher = {Gabler},
pages = {97-107},
location = {Wiesbaden}
}';
Method: (Demo)
$pattern='/^#([^{]+)\{([^,]+),\s*$|^\s*([^\R#=]+) = \{(.*?)}/ms';
if(preg_match_all($pattern,$bibtex,$out,PREG_SET_ORDER)){
foreach($out as $line){
if(isset($line[1])){
if(!isset($line[3])){ // this is the starting line of a new set
if(isset($temp)){
$result[]=$temp; // send $temp data to permanent storage
}
$temp=['type'=>$line[1],'unique_name'=>$line[2]]; // declare fresh new $temp
}else{
$temp[$line[3]]=$line[4]; // continue to store the $temp data
}
}
}
$result[]=$temp; // store the final $temp data
}
var_export($result);
Output:
array (
0 =>
array (
'type' => 'BOOK',
'unique_name' => 'ko',
'title' => 'Wissenschaftlich schreiben leicht gemacht',
'publisher' => 'Haupt',
'year' => '2011',
'author' => 'Kornmeier, M.',
'number' => '3154',
'series' => 'UTB',
'address' => 'Bern',
'edition' => '4',
'subtitle' => 'für Bachelor, Master und Dissertation',
),
1 =>
array (
'type' => 'BOOK',
'unique_name' => 'nial',
'title' => 'Wissenschaftliche Arbeiten schreiben mit Word 2010',
'publisher' => 'Addison Wesley',
'year' => '2011',
'author' => 'Nicol, N. and Albrecht, R.',
'address' => 'München',
'edition' => '7',
),
2 =>
array (
'type' => 'ARTICLE',
'unique_name' => 'shome',
'author' => 'Scholz, S. and Menzl, S.',
'title' => 'Alle Wege führen nach Rom',
'journal' => 'Medizin Produkte Journal',
'year' => '2011',
'volume' => '18',
'pages' => '243-254',
'subtitle' => 'ein Vergleich der regulatorischen Anforderungen und Medizinprodukte
in Europa und den USA',
'issue' => '4',
),
3 =>
array (
'type' => 'INBOOK',
'unique_name' => 'shu',
'author' => 'Schulz, C.',
'title' => 'Corporate Finance für den Mittelstand',
'booktitle' => 'Praxishandbuch Firmenkundengeschäft',
'year' => '2010',
'editor' => 'Hilse, J. and Netzel, W and Simmert, D.B.',
'booksubtitle' => 'Geschäftsfelder Risikomanagement Marketing',
'publisher' => 'Gabler',
'pages' => '97-107',
'location' => 'Wiesbaden',
),
)
Here is the site that I extracted new sample input strings from.

get integer / float from string in PHP

I ran into an issue with a data feed I need to import where for some reason the feed producer has decided to provide data that should clearly be either INT or FLOAT as strings-- like this:
$CASES_SOLD = "THREE";
$CASES_STOCKED = "FOUR";
Is there a way in PHP to interpret the text string as the actual integer?
EDIT: I should be more clear-- I need to have the $cases_sold etc. as an integer-- so I can then manipulate them as digits, store in database as INT, etc.
Use an associative array, for example:
$map = array("ONE" => 1, "TWO" => 2, "THREE" => 3, "FOUR" => 4);
$CASES_SOLD = $map["THREE"]; // 3
If you are only interested by "converting" one to nine, you may use the following code:
$convert = array('one' => 1,
'two' => 2,
'three' => 3,
'four' => 4,
'five' => 5,
'six' => 6,
'seven' => 7,
'eight' => 8,
'nine' => 9
);
echo $convert[strtolower($CASES_SOLD)]; // will display 3
If you only need the base 10 numerals, just make a map
$numberMap = array(
'ONE' => 1
, 'TWO' => 2
, 'THREE' => 3
// etc..
);
$number = $numberMap[$CASES_SOLD];
// $number == 3'
If you need something more complex, like interpreting Four Thousand Two Hundred Fifty Eight into 4258 then you'll need to roll up your sleeves and look at this related question.
Impress your fellow programmers by handling this in a totally obtuse way:
<?php
$text = 'four';
if(ereg("[[.$text.]]", "0123456789", $m)) {
$value = (int) $m[0];
echo $value;
}
?>
You need a list of numbers in english and then replace to string, but, you should play with 'thousand' and 'million' clause where must check if after string 'thousend-three' and remove integer from string.
You should play with this function and try change if-else and add some functionality for good conversion:
I'm writing now a simple code for basic, but you know others what should change, play!
Look at million, thousand and string AND, it should be change if no in string like '1345'. Than replace with str_replace each of them separaterly and join them to integer.
function conv($string)
{
$conv = array(
'ONE' => 1,
'TWO' => 2,
'THREE' => 3,
'FOUR' => 4,
'FIVE' => 5,
'SIX' => 6,
'SEVEN' => 7,
'EIGHT' => 8,
'NINE' => 9,
'TEN' => 10,
'ELEVEN' => 11,
'TWELVE' => 12,
'THIRTEEN' => 13,
'FOURTEEN' => 14,
'FIFTEEN' => 15,
'SIXTEEN' => 16,
'SEVENTEEN' => 17,
'EIGHTEEN' => 18,
'NINETEEN' => 19,
'TWENTY' => 20,
'THIRTY' => 30,
'FORTY' => 40,
'FIFTY' => 50,
'SIXTY' => 60,
'SEVENTY' => 70,
'EIGTHY' => 80,
'NINETY' => 90,
'HUNDRED' => 00,
'AND' => '',
'THOUSAND' => 000
'MILLION' => 000000,
);
if (stristr('-', $string))
{
$val = explode('-', $string);
#hardcode some programming logic for checkers if thousands, should if trim zero or not, check if another values
foreach ($conv as $conv_k => $conv_v)
{
$string[] = str_replace($conv_k, $conv_v, $string);
}
return join($string);
}
else
{
foreach ($conv as $conv_k => $conv_v)
{
$string[] = str_replace($conv_k, $conv_v, $string);
}
return join($string);
}
}
Basically what you want is to write a parser for the formal grammar that represents written numbers (up to some finite upper bound). Depending on how high you need to go, the parser could be as trivial as
$numbers = ('zero', 'one', 'two', 'three');
$input = 'TWO';
$result = array_search(strtolower($input), $numbers);
...or as involved as a full-blown parser generated by a tool as ANTLR. Since you probably only need to process relatively small numbers, the most practical solution might be to manually hand-code a small parser. You can take a look here for the ready-made grammar and implement it in PHP.
This is similar to Converting words to numbers in PHP
PHP doesn't have built in conversion functionality. You'd have to build your own logic based on switch statements or otherwise.
Or use an existing library like:
http://www.phpclasses.org/package/7082-PHP-Convert-a-string-of-English-words-to-numbers.html

how to replace text in a mysql database content array

im trying to get rid of unneccesary text in my database content.My code looks like this:
if(mysql_num_rows($result))
$items[] = array();
while($row = mysql_fetch_assoc($result)) {
$items[] = array('id' => $row['id'], 'cat' => $row['cat'], 'type' => $row['type'], 'name' => $row['name'], 'sub_title' => $row['sub_title'], 'display_date' => $row['display_date'], 'slug' => $row['slug'], 'ticket_url' => $row['ticket_url'], 'status' => $row['status'], 'content' => $row['content'], 'display_until' => $row['display_until'], 'photo' => $row['photo'], 'thumb' => $row['thumb']);
$removals = array('\n','\r','\t','<\/div>\r\n');
$spaces = "";
$parsedText = str_replace($removals, $spaces, $items);
}
echo json_encode(array('events'=>$items));
And the content then displays like this:
{"events":[[],{"id":"66","cat":"9","type":"2","name":"Oileán - A Celebration of the Blasket Islands","sub_title":"National Folk Theatre","display_date":"Tues 4th - Thurs 6th May at 8.30pm","slug":"This production celebrates life on the Blasket Islands in times past, exploring the way of life of the islanders and their spirit of survival. Oileán captures the essence of this island community, their traditions and customs, their wealth of song and story, their love of life and their strong kinship with one another. ","ticket_url":"","status":"1","content":"
\r\n\tPresented by the members of the National Folk Theatre of Ireland</strong>, this production celebrates and explores Blasket Island living while also challenging our own notions of identity as contemporary islanders. </div>\r\n
\r\n\t </div>\r\n
\r\n\tPremiered in 2003, Oileán</strong></em> marked the 50th</sup> anniversary of the departure of the Blasket Islanders to the mainland. The Great Blasket Island, located off the coast of West Kerry still retains an almost mystical significance for many, both from Ireland and abroad. The way of life of the islanders and their spirit of survival is framed in this production, which captures the essence of this island community, their traditions and customs, their wealth of song and story, their love of life and their strong kinship with one another. </div>\r\n
\r\n\t </div>\r\n
\r\n\tOileán</i></b> is delivered in the unique Siamsa style through the medium of dance, mime, music and song.</div>\r\n
\r\n\t </div>\r\n
\r\n\t
\r\n\t\t </div>\r\n\t
\r\n\t\tPlease note that due to the popularity of performances by the National Folk Theatre</strong>, some productions may be sold out well in advance and tickets may not be available on-line. However, we often have returns and tickets may be available nearer to the day of a performance</strong>. Please contact us directly by phone on: +353 (0)66 7123055.</em></div>\r\n\t
\r\n\t\t </div>\r\n\t
\r\n\t\t </div>\r\n</div>\r\n","display_until":"20100504","photo":"1269869378-oilean_side.jpg","thumb":"1269869378-oilean_thumb.jpg"},
The above display is the first item in the DB.
Im trying the replace all the \r , \n , etc in the above content?How can i go about this?Is what i have allready on the right track?
2 things
if(mysql_num_rows($result))
$items = array(); // not $items[], that would set the first item as an array
while($row = mysql_fetch_assoc($result)) {
$removals = array("\n","\r","\t","<\/div>\r\n");
$spaces = "";
$items[] = array(
'id' => $row['id'],
'cat' => $row['cat'],
'type' => $row['type'],
'name' => $row['name'],
'sub_title' => $row['sub_title'],
'display_date' => $row['display_date'],
'slug' => $row['slug'],
'ticket_url' => $row['ticket_url'],
'status' => $row['status'],
// replace the content here
// youll want to use preg_replace though otherwise youll end up with multiple </div>'s
'content' => str_replace( $removals, $spaces, $row['content'] ),
'display_until' => $row['display_until'],
'photo' => $row['photo'],
'thumb' => $row['thumb']
);
}
echo json_encode(array('events'=>$items));

Categories