Replacing characters at start/end of string with PHP's ltrim/rtrim - php

I am looking to clean whitespace and hyphen characters from the start/end of a string.
I have the following test code:
$sample_titles = array(
'— — -Daisy Chain –',
'Ocarina for a Mermaid –',
' –—Another for a Sailor - '
);
foreach ( $sample_titles as $title ) {
$updated_title = ltrim( $title, ' -–—' );
$updated_title = rtrim( $updated_title, ' -–—' );
echo $updated_title . '<br/>';
}
This correctly outputs:
Daisy Chain
Ocarina for a Mermaid
Another for a Sailor
However, when I apply the same ltrim/rtrim logic in a foreach loop (over post titles, I'm "cleaning" imported data, the rest of the code is irrelevant) like this:
foreach ( $product_ids as $key => $product_id ) {
$title = get_the_title( $product_id );
$updated_title = ltrim( $title, ' -–—' );
$updated_title = rtrim( $updated_title, ' -–—' );
echo $updated_title . '<br/>';
};
I still end up with the hyphens/dashes/whitespace like this:
Orb 3 –
Ocarina for a Mermaid –
Mini Marina –
Any ideas why this works in one context but not the other?

Simply wrapping the title grab function in html_entity_decode() fixed the issue I was having:
$product_title = html_entity_decode( get_the_title( $product_id ) );

Related

Wordpress taxonomy last child separated by "en" instead of comma

I'm trying to create a shortcode that outputs my custom taxonomies, separated by a comma, but i want the last comma to be "en" instead of a comma. So like this:
taxonomy, taxonomy, taxonomy en taxonomy
So far i have this:
// Assortiment shortcode
function verlichting_type( ){
$terms = get_the_terms( $post->ID, 'verlichting_type' );
foreach($terms as $term) {
$entry_terms .= $term->name . ', ';
}
$entry_terms = rtrim( $entry_terms, ', ' );
return '<span class="verlichting__type"> ' . $entry_terms . ' </span>';
}
add_shortcode( 'verlichting_type', 'verlichting_type' );
WordPress already have custom printf function with localize the output
So if your site language is Francais means
wp_sprintf_l( '%l', ['Hello', 'world', 'never', 'give', 'up'] )
The above code will output
Hello, world, never, give, et up
For Espanol:
Hello, world, never, give y up
As you noted based on the language the last comma will be added/removed
As I dont have an example of the $terms or $entry_terms variable I had to make up some dummy data, but I think you should be able to extract my example and place it into your code.
I made use of the ternary operator (https://www.php.net/manual/en/language.operators.comparison.php) to determine whether or not the final comma should be ',' or 'en':
<?php
function verlichting_type() {
$entry_terms = "";
$terms = [
(object)['name' => 'taxonomy'],
(object)['name' => 'taxonomy'],
(object)['name' => 'taxonomy'],
(object)['name' => 'taxonomy']
];
echo '<span class="verlichting__type">';
foreach ( $terms as $index => $term) {
$enIndex = sizeof($terms) - 2;
$end = (isset($terms[$enIndex]) && $index == $enIndex ? ' en ' : ', ');
$entry_terms .= $term->name . $end;
}
$entry_terms = rtrim( $entry_terms, ', ' );
return $entry_terms . '</span>';
}
This outputs:
<span class="verlichting__type">taxonomy, taxonomy, taxonomy en taxonomy</span>
This should work with any array length, e.g. if $terms only has 2 elements:
<span class="verlichting__type">taxonomy en taxonomy</span>
Or 1 element:
<span class="verlichting__type">taxonomy</span>

Manipulate and sort the term names of a product attribute in Woocommerce

I'm trying to sort names in alphabetical order after a reverse array.
It's a code done for ordering last name/first name in right order.
A few bugs, (like with names with middle names) but it works except the sorting.
Here is the code:
<?php
$terms = get_terms( 'pa_artist' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
echo '<ul class="artists">';
foreach ( $terms as $term ) {
$array = explode(" ", $term->name);
if ($array[3]) {
$array[3] = strtoupper($array[3]);
$array[3] = "<strong>".$array[3]."</strong>";
}
elseif ($array[2]) {
$array[2] = strtoupper($array[2]);
$array[2] = "<strong>".$array[2]."</strong>";
} elseif ($array[1]) {
$array[1] = strtoupper($array[1]);
$array[1] = "<strong>".$array[1]."</strong>";
} else {
$array[0] = strtoupper($array[0]);
$array[0] = "<strong>".$array[0]."</strong>";
}
$rarray = array_reverse($array);
sort($rarray);
echo '<li>' . implode(" ", $rarray) . '</li>';
}
echo '</ul>';
}
For now the names are ordered as if the reverse was never done.
Some examples, at first it showed like this:
Auguste Renoir
Pablo Picasso
Paul Gauguin
After the reverse and If strings, it's like this:
RENOIR Auguste
PICASSO Pablo
GAUGUIN Paul
When i need it:
GAUGUIN Paul
PICASSO Pablo
RENOIR Auguste
I tried every sort fonction, can't make it work… I can't find a way to sort after a reverse array, is it even possible?
It's for a list of names builded with attributes on wordpress/woocommerce.
I already asked that question, got answers that didn't work unfortunately…
There is Something like 150 names that needs ordering.
I'm willing to pay for this, but no-one is interested because it doesn't require much time so won't pay much! (Only got request to redo the whole website…)
Try the following:
$terms = get_terms( [ 'taxonomy' => 'pa_artist', 'hide_empty' => false ] );
$names_html = $terms_data = [];
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
// 1st Loop: Loop through the terms
foreach ( $terms as $term ) {
$fragments = explode( ' ', $term->name );
if( sizeof($fragments) > 1 ) {
// Manipulate and format the term name
$fragment = '<strong>' . strtoupper($fragments[1]) .'</strong>';
$new_term = $fragment . ' ' . $fragments[0];
// 1st array: We set each formatted term name
$names_html[] = $new_term;
// 2nd array: We set the related data as the Url and the original term name
$terms_data[$new_term] = array(
'link' => get_term_link( $term ),
'name' => $term->name,
);
}
}
// Sort the formatted term names
sort($names_html);
// Output
echo '<ul class="artists">';
// 2nd Loop: Loop through the sorted formatted term names
foreach ( $names_html as $name_html ) {
$link = $terms_data[$name_html]['link'];
$title = sprintf( __( 'View all post filed under %s', 'my_localization_domain' ), $terms_data[$name_html]['name'] );
echo '<li>' . $name_html . '</li>';
}
echo '</ul>';
}
Tested and works.

Join 2 echoes and separate with coma - implode, array

I've got 2 variables. First is coming from the taxonomy and outputs the taxonomy term and the second outputs the custom field:
$address_city = get_custom_field( 'address_city' );
echo '<span>' . $address_city . '</span>';
$terms = get_the_terms($post->id, 'listing_country');
foreach ( $terms as $term ) {
echo '<span>' . $term->name . '</span>';
}
The result of this looks like this: CityCountry
I'm trying to figure out how to separate these two echos with a single coma ,, so the result is as follows: City, Country
I've been trying to play around with the implode() and array() , but I just can't figure out how to get this done without errors.
$address_city = get_custom_field( 'address_city' );
$arr[0] = '<span>' . $address_city . '</span>';
$terms = get_the_terms($post->id, 'listing_country');
foreach ( $terms as $term ) {
$arr[1] = '<span>' . $term->name . '</span>';
}
echo implode(", ", $arr);
try this code it will help you for sure..

Prevent recursion on replacing elements

at first: No, this is not a duplicate. I know that there are some possibilities to search for elements in a HTML-page, but this is not really my problem.
I will outline my problem:
My PHP-code is for reasons I can not change called 2-3 times on every page-rendering.
My code crawls the html-content for specific words and replaces them with a link.
To archive this I am using https://github.com/sunra/php-simple-html-dom-parser .
This is my source:
foreach ( $dom->find( 'text' ) as $element ) {
//$config['exclusions'] is an array like ['a', 'img']
if ( !in_array( $element->parent()->tag, $config[ 'exclusions' ] ) ) {
foreach ( $markers as $marker ) {
$text = $marker[ 'text' ];
$url = $marker[ 'url' ];
$tip = strip_tags( $marker[ 'excerpt' ] );
$tooltip = ( $tooltip ? "data-uk-tooltip title='$tip'" : "" );
$tmpval = "tmpval-$i";
$element->innertext = preg_replace(
'/\b' . preg_quote( $text, "/" ) . '\b/i',
"<a href='$url' $hrefclass target='$target' $tmpval>\$0</a>",
$element->innertext,
1
);
$element->innertext = str_replace( $tmpval, $tooltip, $element->innertext );
$i++;
}
}
}
The problem is: If the $tooltip contains a word that matches a marker, this word is being replaced. So the result is <a href='foo.html' target='_self' data-uk-tooltip title='<a href='bar.html'...'>\$0</a> which destroys the markup of the page.
So my question: How can I prevent this?
Use lookbehind:
$element->innertext = preg_replace(
'(?<!\w=['"])\b' . preg_quote( $text, "/" ) . '\b/ig',
"<a href='$url' $hrefclass target='$target' $tmpval>\$0</a>",
$element->innertext,
1
);

PHP over trim! Text disappearing! But why?

I just want to display the categories for my blog posts, but to SOME of the categories (and especially if they stand alone, the last bit get's trimmed away ~ "Music" becomes "Mu", and "Adventure" becomes "Adventur" ... any help? Please!
// Category boxes :P
function showcatz() {
global $post;
echo '<div class="categz_wrapper"><div class="categz">';
// get the category IDs assigned to post
$categories = wp_get_post_categories( $post->ID, array( 'fields' => 'ids' ) );
// separator between links
$separator = '</div><div class="categz"> ';
if ( $categories ) {
// List categories
$cat_ids = implode( ',' , $categories );
// Remove ONE category from the list
$kill = array("411,", "411");
$killit = str_replace($kill, "", $cat_ids);
$cats = wp_list_categories( 'title_li=&style=none&echo=0&include=' . $killit);
$cats = rtrim( trim( str_replace( '<br />', $separator, $cats ) ), $separator );
// Only show categories if there is any
if ( $killit ) { echo $cats; }
}
echo '</div></div>';
}
your passing a parameter to rtrim called $separator which has the value </div><div class="categz"> so when the following statement is executed it will remove the following chars from your string. div<>clastegz
rtrim( str_replace( '<br />', $separator, $cats ) ), $separator );
Solution, remove the second parameter to rtrim

Categories