I have the following string. I need to find the position of the last white space.
I have tried the following code:
for ($i = 410; $i < 420; $i++) {
if ($body[$i] == ' ') {
$lastCharacter = $i;
break;
}
}
But it does not return the correct white space position. It return a position in middle of a word.
Dans cette septième étape, les coureurs vont relier Montpellier et
Albi, passant au milieu des vignes de l'arrière-pays pour faire la
jonction entre les Alpes et les Pyrénées, traversant des paysages qui
font toute la saveur du Tour. Dernière étape un peu plate avant un
week-end placé sous le signe de la montagne. Des ascensions de col, la
foule amassée sur les côtés, souffrant avec leu...
$lastSpace = strrpos($string," ");
Doc: strrpos
Use strrpos : http://php.net/manual/en/function.strrpos.php
echo $pos = strrpos($mystring, " ");
Related
I have a little problem, I'm getting around 800 000 datas from a json and I'm trying to insert them into a MongoDB Database. But I reach memory limit (I've set it up to 8GB for testing) while doing this. I think my script isn't optimized but I can't find where. Can you guys help me ? Here is the script :
$jsonResponse = json_decode($content->response);
$datas = $jsonResponse->hits->hits;
// On crée la collection si elle n'éxiste pas
$collection = $connection->createCollection($table->getTableName(), false );
// On enregistre les données dans la collection
foreach ($datas as $data)
{
if(!empty($data) || $data)
{
$document['_id'] = $data->_id; // ID netwoof unique
$document['_updated'] = substr($data->_source->_updated, 0, -3); // Date de dernière MàJ des données
$document['_url'] = $data->_source->_url; // Start URL
// On enregistre ensuite chaque champs définis dans le dashboard
foreach ($fields as $field)
{
// On récupère le nom du champs netwoof
$containerFieldName = $field->getContainerFieldName();
// On fait correspondre notre champ db avec celui netwoof
if( isset( $data->_source->$containerFieldName ) && (!empty($data->_source->$containerFieldName) || $data->_source->$containerFieldName == 0 ) )
$document[$field->getFieldName()] = $data->_source->$containerFieldName;
/*else
$document[$field->getFieldName()] = null;*/
}
foreach ($customFields as $customField)
{
if(!empty($customField->getFieldValue()))
$document[$customField->getFieldName()] = $customField->getFieldValue();
}
// Enregistrement des données
$collection->save($document);
}
// On réinitialise la variable
unset($document);
}
Thanks all for your answer and sorry for my english.
I'm stuck; I want to not have the "-" separator on my last item! How can I do that? I know I'm supposed to use count, but I don't know how to go further.
$report = array();
$job = null; //on met la variable a zero
$i = null;
//On extrait les valeurs dans un nouveau tableau à l'aide d'une boucle :
foreach ($values_collaborateurs as $key_collab => $row_collab)//id collab prendra chaque valeur du tableau
{
//ici ne pas mettre de report[key_collab]
//exit(var_dump($values_collaborateurs));
$report[] = $row_collab; // la valeur de id collab = indice collab
//On re extrait les valeurs: boucle du table mission:
//pour chaque élément de $values_missions => id-mission
foreach($values_missions as $key_mission => $row_mission)
{
//ici ne pas mettre de report[key_missions]
// ici la condition de recherche
if ($row_collab[0] == $row_mission[1])
{
$job .= $row_mission[2]." - ";// .= concatenation pr dire s'ajoute a row mission la valeur de job
// rempli le job par des valeurs
}
}
$report[$key_collab][] = $job; //$report = table qui contient chq valeur des key collab, et tout ça tu le stock ds $job
$i = null;
$job = null; //stop - remet le cycle job a zero pour recommencer a null
}
print_r("<pre>\n");
print_r($report);
print_r("<pre>\n");
printf("<br>\n");//passage a la ligne
?>
U can delete last two chars after foreach is completed using strlen...
foreach($values_missions as $key_mission => $row_mission)
{
//ici ne pas mettre de report[key_missions]
// ici la condition de recherche
if ($row_collab[0] == $row_mission[1])
{
$job .= $row_mission[2]." - ";// .= concatenation pr dire s'ajoute a row mission la valeur de job
// rempli le job par des valeurs
}
}
$job = substr($job,0,strlen($job)-2);
Other solution is:
$jobs[] = $row_mission[2]; // instead of: $job .= $row_mission[2] . " - ";
and after foreach will ended:
$job = implode(" - ", $jobs);
Use count() to determine the total number of items and compare it with a counter ($current_mission) that you increment each iteration step.
Then you can append the separator only if the current item is not the last one:
$current_mission = 1;
$total_missions = count($values_missions);
foreach($values_missions as $key_mission => $row_mission)
{
//ici ne pas mettre de report[key_missions]
// ici la condition de recherche
if ($row_collab[0] == $row_mission[1])
{
$job .= $row_mission[2];// .= concatenation pr dire s'ajoute a row mission la valeur de job
if ($current_mission < $total_missions) {
$job .= ' - ';
}
// rempli le job par des valeurs
}
++$current_mission;
}
An alternative is to build an array of strings and use implode().
I highly suggest to not build an array and then use implode, as it's too much overhead for both CPU and memory. If you go for substr($job,0,strlen($job)-2); you are better off with substr($job, 0, -3);, which does exactly the same.
If it's easier to read for you, you can do $job .= ' - ' . $row_mission[2]; and then substr($job, 3);.
On a side note, your code looks buggy:
You use $report[] = $row_collab;, and later $report[$key_collab][], which means you are using $reportboth as un-indexed array and associative array. That your data looks right might just be a coincidence, because if $key_collaband $row_collab have the same value, they overwrite each other.
I'm using Codeigniter.
I want to get in my database all the dates that are between two dates
The result for my function is always an empty array.
In my DB dates are this format: 2015-10-21
My model
public function lireListeAchats($selection = "*", $date_debut, $date_fin, $champs_order = "id", $direction_ordre = "ASC", $nombre_limite = NULL, $debut_limite = NULL){
$conditions = "date_achat BETWEEN $date_debut AND $date_fin";
$retour= $this->db->select($selection)
/*à partir de quelle table*/
->from($this->table)
/*déterminer des conditions spécifiques*/
->where($conditions)
/*déterminer un ordre précis*/
->order_by($champs_order, $direction_ordre)
/*déterminer une limite*/
->limit($nombre_limite, $debut_limite)
/*obtenir les résultats (va de pair avec result()*/
->get()
/*retourner les résultats sous forme de tableau*/
->result_array();
return $retour;
}
$date_debut and $date_fin return in this format: 2015-10-01
It's because of $date_debut AND $date_fin, those variables are strings.
Wrap them in quotes '$date_debut' AND '$date_fin'
MySQL is interpreting 2015-10-01 as 2015 minus 10 minus 01.
Use CodeIgniter's error checking:
https://ellislab.com/codeigniter/user-guide/general/errors.html
You have a typo here. It should be either return or retour. Return seems to be better than retour.
public function lireListeAchats($selection = "*", $date_debut, $date_fin, $champs_order = "id", $direction_ordre = "ASC", $nombre_limite = NULL, $debut_limite = NULL){
$conditions = "date_achat BETWEEN $date_debut AND $date_fin";
$return= $this->db->select($selection)
/*à partir de quelle table*/
->from($this->table)
/*déterminer des conditions spécifiques*/
->where($conditions)
/*déterminer un ordre précis*/
->order_by($champs_order, $direction_ordre)
/*déterminer une limite*/
->limit($nombre_limite, $debut_limite)
/*obtenir les résultats (va de pair avec result()*/
->get()
/*retourner les résultats sous forme de tableau*/
->result_array();
return $return;
I will try to explain my case.
I would like to change the wpseo_title, wpseo_metakey, wpseo_metadesc, wpseo_opengraph_type, wpseo_opengraph_image, wpseo_title, and wpseo_opengraph_image_size on the "archive-page" of "custom post"
Because yoast plugin not translated meta tags inside "archive" post. And i need to translate all
I have this code:
function get_archive_seo() {
include 'seo_archive.php';
$tipoSel = get_post_type(get_the_ID());
if(is_post_type_archive( $tipoSel )){
foreach ($traduccionesArchive as $keyTipo => $tipo){
foreach ($tipo as $keyMeta => $palabra){
if($keyMeta == 'opengraph_type' || $keyMeta == 'opengraph_image_size') continue;
icl_register_string ('my-theme', $keyTipo." - ".$keyMeta, $palabra);
}
}
foreach ($traduccionesArchive[$tipoSel] as $key => $palabra){
add_filter( 'wpseo_'.$key, function($nombre) use ( $palabra, $tipoSel, $key ) {
if($key == 'opengraph_type' || $key == 'opengraph_image_size') return $palabra;
return icl_t('my-theme', $tipoSel." - ".$key, $palabra);
});
}
}
}
add_filter( 'wp_head', 'get_archive_seo');
And this is the "seo_archive.php":
$traduccionesArchive['hoteles']['title'] = 'Hotel, Vacaciones en Andalucia';
$traduccionesArchive['hoteles']['metakey'] = 'palabra1, palabra2, palabra3';
$traduccionesArchive['hoteles']['metadesc'] = 'Mapa de Hotel en Andalucia, Costa del Sol, Costa de la Luz y Sierra de Grazalema. El lugar ideal para tus vacaciones.';
$traduccionesArchive['hoteles']['opengraph_type'] = 'object';
$traduccionesArchive['hoteles']['opengraph_image'] = 'http://www.hotel.com/img/logo.png';
$traduccionesArchive['hoteles']['opengraph_image_size'] = 100;
$traduccionesArchive['apartamentos']['title'] = 'Apartamentos de vacaciones Costa del Sol ';
$traduccionesArchive['apartamentos']['metakey'] = 'palabra1, palabra2, palabra3';
$traduccionesArchive['apartamentos']['metadesc'] = 'Mapa de localizacion de los Apartamentos Vacacionales de Hotel. Disfruta de tus vacaciones en familia en la Costa del Sol.';
$traduccionesArchive['apartamentos']['opengraph_type'] = 'object';
$traduccionesArchive['apartamentos']['opengraph_image'] = 'http://www.hotel.com/img/logo.png';
$traduccionesArchive['apartamentos']['opengraph_image_size'] = 100;
$traduccionesArchive['destinos']['title'] = 'Mapa de localizacion de Hotel, Andalucia';
$traduccionesArchive['destinos']['metakey'] = 'palabra1, palabra2, palabra3';
$traduccionesArchive['destinos']['metadesc'] = 'Mapa de Hoteles en Andalucia, en los destinos vacacionales de Costa del Sol, Costa de la Luz y Sierra de Grazalema Andalucia.';
$traduccionesArchive['destinos']['opengraph_type'] = 'object';
$traduccionesArchive['destinos']['opengraph_image'] = 'http://www.hotel.com/img/logo.png';
$traduccionesArchive['destinos']['opengraph_image_size'] = 100;
$traduccionesArchive['ofertas']['title'] = 'Ofertas Hotel Costa del Sol, Costa de la Luz ';
$traduccionesArchive['ofertas']['metakey'] = 'palabra1, palabra2, palabra3';
$traduccionesArchive['ofertas']['metadesc'] = 'Ahorra en tus vacaciones con las ofertas en nuestros hoteles de la Costa del Sol, Costa de la Luz y Andalucia.';
$traduccionesArchive['ofertas']['opengraph_type'] = 'object';
$traduccionesArchive['ofertas']['opengraph_image'] = 'http://www.hotel.com/img/logo.png';
$traduccionesArchive['ofertas']['opengraph_image_size'] = 100;
But now, it not works, but in the past works fine, the filter is form module yoast SEO https://yoast.com/wordpress/plugins/seo/
Y tried with this Wordpress: How to return value when use add_filter?
I'm a little confused because this:
add_filter( 'wpseo_title', function(){return 'foo';}
Works outside the get_archive_seo functions, but not works inside function.
Can anybody help me?
You can use like this, this may help to you.
function title_function_name($title) {
$title = "Your title write here";
return $title;
}
add_filter('wp_title', 'title_function_name', 15);
if (!has_filter('wpseo_title'))
add_filter('wpseo_title', 'title_function_name', 15);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a web site and my problem is about the section "Voter".
When we vote, we doesn't have the gift and the error come about my line 121:
PHP Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in /home/pvpdream/public_html/voter/recompenses.php on line 121
I give you the script:
<?php
if ($_SESSION['out'] == true)
{
$inputString = $_SESSION['Pseudo_String'];
$pseudo = $inputString;
$selection = $bdd -> prepare('SELECT * FROM joueurs WHERE user_pseudo = :user_pseudo');
$selection -> bindParam(':user_pseudo', $inputString);
$selection -> execute();
$MonPersonnage = $selection -> fetch(PDO::FETCH_OBJ);
$NomPersonnage = $MonPersonnage->user_pseudo;
#### POINTS
$NbrPoints = $MonPersonnage->user_points;
$NbrVote = $MonPersonnage->vote;
$ApresVote = $NbrPoints + $Points_par_vote;
$vote = $NbrVote +1 ;
#### TEMPS
$date = time();
$HeureVote = $MonPersonnage->date_vote;
$EcartMinutes = ($date - $HeureVote)/60;
#### IP
$ip = $_SERVER['REMOTE_ADDR'];
if ($EcartMinutes > 180)
{
if($_GET['verification'] == "items" && $_GET['serveur'] == 'f')
{
$serveur = 'f';
$update = $bdd->prepare('UPDATE joueurs SET date_vote = :date_vote, vote = :vote WHERE user_pseudo = :user_pseudo');
$update -> bindParam(':date_vote', $date);
$update -> bindParam(':vote', $vote);
$update -> bindParam(':user_pseudo', $NomPersonnage);
$update -> execute();
$update = $bdd->prepare('UPDATE vote_ip SET date_vote = :date_vote WHERE ip = :ip');
$update -> bindParam(':date_vote', $date);
$update -> bindParam(':ip', $ip);
$update -> execute();
##################################### Probabilités
$query = $bdd->prepare('SELECT SUM(p) AS somme FROM probabilites');
$query->execute();
$string = $query->fetch();
$nbr_items = $string['somme'];
$query = $bdd->prepare ("SELECT * FROM probabilites WHERE serveur = '".$serveur."'");
$query->execute();
$prob = 1000;
$rand = mt_rand(0, $prob);
$items = array ();
while($resultats = $query->fetch(PDO::FETCH_OBJ))
{
$items[$resultats->quantite.'|'.$resultats->nom.'|'.$resultats->commande.''] = $resultats->p / $nbr_items;
}
asort($items);
$i = 0;
foreach ($items as $name => $value)
{
if ($rand <= $i+=($value * $prob))
{
$item = $name;
break;
}
}
list($quantite, $nom, $commande) = explode("|", $item);
# Exécution des requêtes items
$commande_exp = explode(" ", $commande);
if($commande_exp[0] == 'POINTS')
{
$requete = str_replace("POINTS ", "", $commande);
$VoteBoutique = $NbrPoints + $requete;
echo '<br /><div class="alert alert-success"><b> Succès</b> : '.$pseudo.' vous venez d\'obtenir le cadeau suivant : <b> '.$quantite.' '.$nom.' </b>.</div>';
$update = $bdd->prepare('UPDATE joueurs SET user_points = :user_points WHERE user_pseudo = :user_pseudo');
$update -> bindParam(':user_points', $VoteBoutique);
$update -> bindParam(':user_pseudo', $pseudo);
$update -> execute();
$connexion_1->call("runConsoleCommand", array("broadcast ".$pseudo." vient de gagner ".$quantite." ".$nom." en votant pour le serveur."));
/*$connexion_2->call("runConsoleCommand", array("broadcast ".$pseudo." vient de gagner ".$quantite." ".$nom." en votant pour le serveur."));
$connexion_3->call("runConsoleCommand", array("broadcast ".$pseudo." vient de gagner ".$quantite." ".$nom." en votant pour le serveur."));
$connexion_4->call("runConsoleCommand", array("broadcast ".$pseudo." vient de gagner ".$quantite." ".$nom." en votant pour le serveur."));
$connexion_5->call("runConsoleCommand", array("broadcast ".$pseudo." vient de gagner ".$quantite." ".$nom." en votant pour le serveur."));
$connexion_6->call("runConsoleCommand", array("broadcast ".$pseudo." vient de gagner ".$quantite." ".$nom." en votant pour le serveur."));
$connexion_7->call("runConsoleCommand", array("broadcast ".$pseudo." vient de gagner ".$quantite." ".$nom." en votant pour le serveur."));
$connexion_8->call("runConsoleCommand", array("broadcast ".$pseudo." vient de gagner ".$quantite." ".$nom." en votant pour le serveur."));
*/}
else
{
echo '<br /><div class="alert alert-success"><b> Succès</b> : Vous venez d\'obtenir le cadeau suivant : <b> '.$quantite.' '.$nom.' </b>.</div>';
$commande = str_replace('pseudo_var', $pseudo, $commande);
$connexion_1->call("runConsoleCommand", array("".$commande.""));
$connexion_1->call("runConsoleCommand", array("broadcast &c&lFélicitation &b&l".$pseudo." vient de gagner ".$quantite." ".$nom." en votant pour le serveur.));
}
$_SESSION['out'] = false;
}
}
else
{
echo '<br /><div class="alert alert-danger">Vous devez attendre 180 minutes afin de pouvoir revoter.</div>';
}
}
elseif ($_SESSION['out'] == false)
{
echo '<br /><div class="alert alert-danger"><b> Erreur</b>: Votre récompense a déjà été obtenue.</div>';
}
?>
You can see the error from the syntax highlighting in your question. It's this line:
$connexion_1->call("runConsoleCommand", array("broadcast &c&lFélicitation &b&l".$pseudo." vient de gagner ".$quantite." ".$nom." en votant pour le serveur.));
You need an extra " at the end, so it would be:
$connexion_1->call("runConsoleCommand", array("broadcast &c&lFélicitation &b&l".$pseudo." vient de gagner ".$quantite." ".$nom." en votant pour le serveur."));