Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Kane Stoboi
21,919 PointsSorting an array excluding html tags
I have an array of strings, each of which may contain a <i> HTML tag.
E.g.
reference[0] = "<i>some text</i> Some more text";
reference[1] = "this is the second element";
reference[2] = "Some more text";
reference[3] = "<i>another</i> string";
What I would like to do is to sort the array alphabetically but exclude the <i> tags from being included in the sorting.
Any suggestions?
3 Answers
cesare
15,180 Points<?php
// the Function
function compareStrings($a, $b) {
return strcasecmp(strip_tags($a), strip_tags($b));
}
// your Array
$reference = array("<s>all</s>", "<i>your</i>", "<b>elements</b>");
// the Magic
usort($reference, "compareStrings");
?>
cesare
15,180 PointsUse this PHP Native Function to "remove" html tags temporarily:
strip_tags($array[i]);
Jeffrey van Rossum
2,994 PointsThis might not be the best way, but it works:
<?php
// Your array
$reference = array();
$reference[0] = "<i>some text</i> Some more text";
$reference[1] = "this is the second element";
$reference[2] = "z more text";
$reference[3] = "Some more text";
$reference[4] = "B more text";
$reference[5] = "<i>another</i> string";
// Loop and add filtered version
foreach( $reference as $key => $ref ){
$reference[$key] = array();
$reference[$key]['html'] = $ref;
$reference[$key]['filter'] = strip_tags( $ref );
}
// Function to compare
function sort_it( $a, $b ) {
return strcmp( $a["html"], $b["filter"] );
}
// Sort
usort( $reference, 'sort_it' );
/*
echo '<pre>';
print_r( $reference );
echo '</pre>';
*/
// Loop & echo
foreach ( $reference as $ref ) {
echo $ref['html'] . '<br>';
}
?>
Again, this might not be the best way, maybe somebody else knows a better solution.
Kane Stoboi
21,919 PointsKane Stoboi
21,919 PointsThanks cesare, that works really well. I've decided to change the array slightly so it is now like this..
and I just want to sort by the "reference" key, I'm having trouble modifying the code to do this.
Jeffrey van Rossum
2,994 PointsJeffrey van Rossum
2,994 PointsThis is a version that will work with your new array. Thanks to Cesare earlier answer of course.
Kane Stoboi
21,919 PointsKane Stoboi
21,919 PointsThanks a lot guys works a treat!