how to check for a linked string inside an array? - php

I have an array, let us say, $breadcrumb = array("home" , "groups", "Create content", "some other element" "so on"); I want to check if it contains a string "Create content" and then unset the string, but my problem is that "Create content" is a link (anchored) and not just a plain string, I tried in_array(), but not successful. How do I look for it, to make it more clear?
Here is my code:
<?php
function phptemplate_breadcrumb($breadcrumb) {
if (!empty($breadcrumb)) {
if(in_array("Create content",$breadcrumb)){
foreach($breadcrumb as $key => $value){
if("Create content" == strip_tags($value)){
unset($breadcrumb[$key]);
}
}
}
}
return '<div class="breadcrumb">'. implode(' › ', $breadcrumb) .'</div>';
}
Note: I know it can be done anyway if I ommit in_array() check but I don't want to loop through the array unecessarily, if the 'Create content' is not in the array.
Edit: actual array is:
array(
[0]=>home
[1]=> groups
[2]=> my group
[3]=> Create content
)
here 'Create content' may occupy any position.
Note: all elements are links (anchored).

If your real array is something like
array(
[0]=> home
[1]=> groups
[2]=> my group
[3]=> Create content
)
then you can try to use preg-grep so as to return all items that match your regExp pattern:
$content_links = preg_grep("/[YOUR REGEXP HERE]/", $breadcrumb);
// if you have matching items
if (0 < sizeof($content_links)) {
// do some stuff - do `foreach` loop or use `array_diff`
}
UPD:
Or even you can use PREG_GREP_INVERT as third parameter and get all items that doens't match RegExp pattern.

Related

Is it possible to concatenate two values in an array together?

I’m new to PHP so this might be a very long questions. First of all I can’t normalise the database the way it has been designed it has to be kept like this. I’ll explain the scenario first: I have locations on a map, those locations can have as many products attached to them as possible. My issue is that I want to concatenate two values together in an array to make them into a string so I can store it in the db and then use it.
I’m having issues with a particular record, this record 1234 is causing me issues. As it has two Ratings attached to it but I need to concatenate them and put them into another array so I can store in my database in a particular field as strings instead of separate ints.
Below is the code, as you’ll see I did a if statement inside the code I want to use to debug what is happening in that particular record.
$ratingString = array();
$rating = 0;
foreach( //not sure if this foreach is related to the question)
if(true == isset($ratingString[$location[‘id’]])){
echo ‘in set’;
$ratingString[$location[‘id’]][‘ratingString’] = strval( $ratingString[$location[‘id’]][‘ratingString’]).’,’.$rating;
}else {
if($location[‘id’] == 1234){
echo ‘not in set’
$ratingString[$location[‘id’]][‘ratingString’] = $rating;
Print_r($ratingString);
} }
When I debug this, it shows me two variables in rating string.
Not in set
string() “ratingString”
array(1){
[1234] =>
array(1) {
[“ratingString”] =>
int(2)
}
}
Not in set
string() “ratingString”
array(1){
[1234] =>
array(1) {
[“ratingString”] =>
int(3)
}
}
So what I need help with, is how could I concatenate the two so that it would be [ratingString] => string 2,3 and how would I change my code so that it would work for all my locations and not just this particular record.

Get sorted value from an array in php

i used kirki drag and drop wordpress plugin for my site to create a sortable list when dragable is enabled.
i was able to create a setting that outputs this array, when i did var_dump for the settings here was what i got
array(3) { [0]=> string(10) "Big Grid 1" [1]=> string(10) "Big Grid 2" [2]=> string(10) "Big Grid 3" }
when in var_dump it sorts correctly when i drag and drop any element, they take there place as sorted in the var_dump array, to me the array given is completely useless till i set values for them .
so the question is how do i output them in php to get sorted just as they where in the array.
i tried switch case but its not working.
here is my code
foreach ($array[0] as $key => $value) {
switch ($key) {
case 'Big grid 1' :
// do something
break ;
case 'Big grid 2' :
// do something
break ;
case 'Big grid 3' :
// do something
break ;
}
}
please i need help on this one.
hope my question was clear.
i am no PHP expert, thus a complex answer would be well appreciated.
not sure what you are trying to do with using switch statement and I'm not really sure what you are trying to accomplish with that code you have,
but as I understand about your question, you just want to output the value of an array,
then you can do something like
$items = array("Big Grid 1","Big Grid 2","Big Grid 3");
$output = '';
foreach ($items as $item ) {
$output .= $item .'<br/>';
}
echo $output; // or return $output if you need a return value

How to correctly parse .ini file with PHP

I am parsing .ini file which looks like this (structure is same just much longer)
It is always 3 lines for one vehicle. Each lines have left site and right site. While left site is always same right site is changing.
00code42=52
00name42=Q7 03/06-05/12 (4L) [V] [S] [3D] [IRE] [52]
00type42=Car
00code43=5F
00name43=Q7 od 06/12 (4L) [V] [S] [3D] [5F]
00type43=Car
What I am doing with it is:
$ini = parse_ini_file('files/models.ini', false, INI_SCANNER_RAW);
foreach($ini as $code => $name)
{
//some code here
}
Each value for each car is somehow important for me and I can get to each it but really specifily and I need your help to find correct logic.
What I need to get:
mCode (from first car it is 00)
code (from first car it is 52)
vehicle (from first car it is Q7 03/06-05/12 (4L))
values from [] (for first car it is V, S, 3D, IRE , 52
vehicle type ( for first car it is "car")
How I get code from right site:
$mcode = substr($code, 0, 2); //$code comes from foreach
echo "MCode:".$mcode;
How I get vehicle type:
echo $name; // $name from foreach
How I parse values like vehicle and values from brackets:
$arr = preg_split('/\h*[][]/', $name, -1, PREG_SPLIT_NO_EMPTY); // $name comes from foreach
array(6) { [0]=> string(19) "Q7 03/06-05/12 (4L)" [1]=> string(1) "V" [2]=> string(1) "S" [3]=> string(2) "3D" [4]=> string(3) "IRE" [5]=> string(2) "52" }
So basicly I can get to each value I need just not sure how to write logic for work with it.
In general I can skip the first line of each car because all values from there is in another lines as well
I need just 2th and 3th line but how can I skip lines like this? (was thinking to do something like :
if($number % 3 == 0) but I dont know how number of lines.
After I get all data I cant just echo it somewhere but I also need to store it in DB so how can I do this if
I will really appriciate your help to find me correct way how to get this data in right cycle and then call function to insert them all to DB.
EDIT:
I was thinking about something like:
http://pastebin.com/C97cx6s0
But this is just structure which not working
If your data is consistent, use array_chunk, array_keys, and array_values
foreach(array_chunk($ini, 3, true) as $data)
{
// $data is an array of just the 3 that are related
$mcode = substr(array_keys($data)[0], 0, 2);
$nameLine = array_values($data)[1];
$typeLine = array_values($data)[2];
//.. parse the name and type lines here.
//.. add to DB
}

php - push array into an array -(pushing both key and the array)

I am trying to add an array to an existing array. I am able to add the array using the array_push . The only problem is that when trying to add array that contains an array keys, it adds an extra array within the existing array.
It might be best if I show to you
foreach ($fields as $f)
{
if ($f == 'Thumbnail')
{
$thumnail = array('Thumbnail' => Assets::getProductThumbnail($row['id'] );
array_push($newrow, $thumnail);
}
else
{
$newrow[$f] = $row[$f];
}
}
The fields array above is part of an array that has been dynamically fed from an SQl query it is then fed into a new array called $newrow. However, to this $newrow array, I need to add the thumbnail array fields .
Below is the output ( using var_dump) from the above code. The only problem with the code is that I don't want to create a seperate array within the arrays. I just need it to be added to the array.
array(4) { ["Product ID"]=> string(7) "1007520"
["SKU"]=> string(5) "G1505"
["Name"]=> string(22) "150mm Oval Scale Ruler"
array(1) { ["Thumbnail"]=> string(77) "thumbnails/products/5036228.jpg" } }
I would really appreciate any advice.
All you really want is:
$newrow['Thumbnail'] = Assets::getProductThumbnail($row['id']);
You can use array_merge function
$newrow = array_merge($newrow, $thumnail);
Alternatively, you can also assign it directly to $newrow:
if ($f == 'Thumbnail')
$newrow[$f] = Assets::getProductThumbnail($row['id']);
else
...
Or if you want your code to be shorter:
foreach($fields as $f)
$newrow[$f] = ($f == 'Thumbnail')? Assets::getProductThumbnail($row['id']) : $row[$f];
But if you're getting paid by number of lines in your code, don't do this, stay on your code :) j/k

How to extract citations from a text (PHP)?

Hello!
I would like to extract all citations from a text. Additionally, the name of the cited person should be extracted. DayLife does this very well.
Example:
“They think it’s ‘game over,’ ” one senior administration official said.
The phrase They think it's 'game over' and the cited person one senior administration official should be extracted.
Do you think that's possible? You can only distinguish between citations and words in quotes if you check whether there's a cited person mentioned.
Example:
“I think it is serious and it is deteriorating,” Admiral Mullen said Sunday on CNN’s “State of the Union” program.
The passage State of the Union is not a quotation. But how do you detect this? a) You check if there's a cited person mentioned. b) You count the blank spaces in the supposed quotation. If there are less than 3 blank spaces it won't be a quotation, right? I would prefer b) since there's not always a cited person named.
How to start?
I would first replace all types of quotes by a single type so that you'll have to check for only one quote mark later.
<?php
$text = '';
$quote_marks = array('“', '”', '„', '»', '«');
$text = str_replace($quote_marks, '"', $text);
?>
Then I would extract all phrases between quotation marks which contain more than 3 blank spaces:
<?php
function extract_quotations($text) {
$result = preg_match_all('/"([^"]+)"/', $text, $found_quotations);
if ($result == TRUE) {
return $found_quotations;
// check for count of blank spaces
}
return array();
}
?>
How could you improve this?
I hope you can help me. Thank you very much in advance!
As ceejayoz already pointed out, this won't fit into a single function. What you're describing in your question (detecting grammatical function of a quote-escaped part of a sentence - i.e. “I think it is serious and it is deteriorating,” vs "State of the Union") would be best solved with a library that can break down natural language into tokens. I am not aware of any such library in PHP, but you can have a look at the project size of something you would use in python: http://www.nltk.org/
I think the best you can do is define a set of syntax rules that you verify manually. What about something like this:
abstract class QuotationExtractor {
protected static $instances;
public static function getAllPossibleQuotations($string) {
$possibleQuotations = array();
foreach (self::$instances as $instance) {
$possibleQuotations = array_merge(
$possibleQuotations,
$instance->extractQuotations($string)
);
}
return $possibleQuotations;
}
public function __construct() {
self::$instances[] = $this;
}
public abstract function extractQuotations($string);
}
class RegexExtractor extends QuotationExtractor {
protected $rules;
public function extractQuotations($string) {
$quotes = array();
foreach ($this->rules as $rule) {
preg_match_all($rule[0], $string, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$quotes[] = array(
'quote' => trim($match[$rule[1]]),
'cited' => trim($match[$rule[2]])
);
}
}
return $quotes;
}
public function addRule($regex, $quoteIndex, $authorIndex) {
$this->rules[] = array($regex, $quoteIndex, $authorIndex);
}
}
$regexExtractor = new RegexExtractor();
$regexExtractor->addRule('/"(.*?)[,.]?\h*"\h*said\h*(.*?)\./', 1, 2);
$regexExtractor->addRule('/"(.*?)\h*"(.*)said/', 1, 2);
$regexExtractor->addRule('/\.\h*(.*)(once)?\h*said[\-]*"(.*?)"/', 3, 1);
class AnotherExtractor extends Quot...
If you have a structure like the above you can run the same text through any/all of them and list the possible quotations to select the correct ones. I've run the code with this thread as input for testing and the result was:
array(4) {
[0]=>
array(2) {
["quote"]=>
string(15) "Not necessarily"
["cited"]=>
string(8) "ceejayoz"
}
[1]=>
array(2) {
["quote"]=>
string(28) "They think it's `game over,'"
["cited"]=>
string(34) "one senior administration official"
}
[2]=>
array(2) {
["quote"]=>
string(46) "I think it is serious and it is deteriorating,"
["cited"]=>
string(14) "Admiral Mullen"
}
[3]=>
array(2) {
["quote"]=>
string(16) "Not necessarily,"
["cited"]=>
string(0) ""
}
}
If there are less than 3 blank spaces it won't be a quotation, right?
"Not necessarily," said ceejayoz.
The passage State of the Union is not a quotation. But how do you detect this? a) You check if there's a cited person mentioned. b) You count the blank spaces in the supposed quotation. If there are less than 3 blank spaces it won't be a quotation, right? I would prefer b) since there's not always a cited person named.
b) doesn't even work for this very example - there are 3 blank spaces in "State of the Union".
A quotation will always have punctuation--either a comma at the end, to signify that the speaker's name or title is to follow, or the end of the sentence (.!?).

Categories