How can I filter an array of strings to remove elements that are prefixes of other elements?

How can I filter an array of strings to remove elements that are prefixes of other elements?

Content Index :

How can I filter an array of strings to remove elements that are prefixes of other elements?
Tag : php , By : demize95
Date : November 27 2020, 09:01 AM

To fix this issue It looks like what you are wanting to do is group the array into sets of strings that extend the other strings in the group, and select the longest string from each group. The groups from the array
$old_array = array('123','234','1234','2345','123456','345','1','12');
1, 12, 123, 1234, 123456
234, 2345
foreach ($old_array as $old) {

    // set a flag to indicate whether the value has already been added
    $matched = false;

    // loop over the new values by reference
    foreach ($new_array as &$new) {

        if ($new == $old) {  // this should prevent duplicate values from being added
            $matched = true; 

        } elseif ((strlen($old) > strlen($new)) && strpos($old, $new) === 0) {
            // if the old string starts with the new string, replace the value
            $new = $old;
            $matched = true;

        } elseif ((strlen($new) > strlen($old)) && strpos($new, $old) === 0) {
            // if the new string starts with the old string don't replace it and don't add it
            $matched = true;
    unset($new); // unset the reference

    if (!$matched) {
        // if no matching strings were found, add the string
        $new_array[] = $old;
sort($old_array, SORT_STRING);
$old_array[] = null;  // append a null to force comparison of the last item
foreach ($old_array as $value) {
    if (isset($current) && !(strpos($value, $current) === 0)) {
        $new_array[] = $current;
    $current = $value;

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How to remove strings from all elements in array?

Tag : ruby , By : wiznick
Date : March 29 2020, 07:55 AM
will be helpful for those in need I think you mean you have an array of strings and they all contain some substring that you want to remove. Non-destructively:
array.map {|s| s.gsub(keyword, '')}

Remove characters and elements from Array of Strings Swift

Tag : ios , By : LUK
Date : March 29 2020, 07:55 AM
hop of those help? I have an array of strings that have been converted from a date into a String from Parse like this: , When you are using
self.timeCreatedString += arrayOfCompontents[0...2]
self.timeCreatedString.append("\(arrayOfCompontents[0]) \(arrayOfCompontents[1]) \(arrayOfCompontents[2])")

How to remove elements from an array using filter() in JavaScript?

Tag : javascript , By : Gerhard Miller
Date : March 29 2020, 07:55 AM
will be helpful for those in need you need to change your filter function, check if each value in arr is in args, if yes return false for it otherwise return true.
function destroyer(arr) {
  // Remove all the values
  var args = Array.from(arguments);
   var arr1 = arr.filter(function(v){
      return (args.indexOf(v) !== -1) ? false : true;        
  return arr;

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

Filter out / remove elements matching criteria from the end of array

Tag : javascript , By : goffi
Date : March 29 2020, 07:55 AM
I wish this helpful for you An alternative is using the function reduceRight along with the Spread syntax.
let removeFromEnd = (arr) => arr.reduceRight((a, b) => ((b !== '' || a.length) ? [b, ...a] : a), []);    

console.log(removeFromEnd(['a', 'b', '', 'c', '', '']));
console.log(removeFromEnd(['a', '', '']));
console.log(removeFromEnd(['', '', '', '', 'c']));
console.log(removeFromEnd(['', '', '', '']));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Remove elements from array using javascript filter

Tag : javascript , By : Anna
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • Making code work with register_globals turned off
  • PHP array indexing: $array[$index] vs $array["$index"] vs $array["{$index}"]
  • PHP4 to PHP5 Migration
  • Making a production build of a PHP project with Subversion
  • Add 1 to a field
  • Better Random Generating PHP
  • Accessing a CONST attribute of series of Classes
  • Locking a SQL Server Database with PHP
  • Version control PHP Web Project
  • How to sell Python to a client/boss/person
  • How to easily consume a web service from PHP
  • How to include PHP files that require an absolute path?
  • Multi-Paradigm Languages
  • PHP Error - Uploading a file
  • MySQL/Apache Error in PHP MySQL query
  • Lightweight IDE for Linux
  • How to search a row that has been joined with another table
  • How to do mysql LEFT JOIN for Google multiple line chart (php, mysql)?
  • Find the two longest strings separated by dash in PHP
  • Cannot access private property with Set method in Symfony
  • How to compare 2 array of PHP objects then fill in empty string if data not match?
  • strtotime gives back false result to strings in an array
  • How to create Url that contain name and id laravel
  • Codeigniter: Models not working with an error: Undefined property: CI_Loader
  • How to use + or - operators as parameters in Doctrine prepared SQL statement?
  • How to run scrapy with url parameters from php on linux debian
  • Preg matching imgur.com links
  • Php - Code comparing value of database to the value send by android app
  • Laravel pagination object in javascript
  • Error in validating message of no votes PHP
  • Symfony site on Azure with ClearDB connection
  • Woocommerce upsell with checkboxes
  • How to login/logout with Hybridauth 3?
  • Convert INT number in PHP
  • php/mysql. selecting 2 common fields in 2 tables
  • Expand an string based on values in an array in PHP
  • When you absolutely have to manually escape SQL in CakePHP 3.4.7
  • Htaccess redirecting wrong page
  • Laravel Optional WHERE clause
  • PHP unpack overlfow variable memory limit
  • How to check the URL's structure using PHP preg_match?
  • PHP preg_replace - text will not be recognized
  • Show image from other domain without showing the domain name - PHP
  • How to run and watch local server at the same time?
  • Access form request from Observer laravel
  • single quote problem with preg_replace_callback
  • How to Create A Unique URL for each product enquiry form for Google Analytics Tracking
  • Laravel email configuration: what am I missing?
  • Assign indexed array values to multidimensional array?
  • Custom WordPress stylesheet not loading
  • Data attribute only returning first value
  • How to list all roles with Permissions,in spatie permission Package?
  • How to achieve this number pattern with n input
  • How to iterate array inside array data in laravel ,output are given below
  • To get output of movie with its genre
  • Extracting some data from a JS object literal string in PHP using Regex
  • axios and vuex are deleting wrong index in array
  • Setting empty CURLOPT_POSTFIELDS
  • Laravel 5.8 use subdomain as API endpoint beside domain.com/api
  • Error while add data in database SQL Server 2016
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com