3

Let's say i have the following string: $test ='abcd.gdda<fsa>dr';

And the following array: $array = array('<','.');

How can i find the positions of the characters that are elements in the $array array? (fastest way possible) and then store and remove them (without leaving NULL values at that specific index)?

Ps. I know that i could use strpos() to check for each element but that would output something like: 9, 5 because the '<' symbol is searched for before the '.' element and that causes the function to believe that the '<' is before '.' in the string. I tried combining this with the sort() function...but i does not work as expected... (it outputs some NULL positions...)

7
  • Instead of strpos() use strrpos(), start looking for string for right to left. So when you replace <, character . will still be on same position. Commented Dec 28, 2013 at 11:22
  • if i use this method...how will i check for all the occurrences? this will always stop after finding the first element... Commented Dec 28, 2013 at 11:27
  • Do you also need to store positions for every search character separately? Or just positions in which any of those characters were found? Commented Dec 28, 2013 at 11:30
  • @Cthulhu yes i do...and in ascending order too Commented Dec 28, 2013 at 11:31
  • Here you have a demo of this duplicated question: PHP Find all occurrences of a substring in a string Commented Dec 28, 2013 at 11:32

5 Answers 5

3

Works with both strings and characters:

<?php
    $test ='abcda.gdda<fsa>dr';
    $array = array('<', '.', 'dr', 'a'); // not also characters but strings can be used
    $pattern = array_map("preg_quote", $array);
    $pattern = implode("|", $pattern);
    preg_match_all("/({$pattern})/", $test, $matches, PREG_OFFSET_CAPTURE);
    array_walk($matches[0], function(&$match) use (&$test)
    {
        $match = $match[1];
    });
    $test = str_replace($array, "", $test);
    print_r($matches[0]); // positions
    echo $test;

Output:

Array
(
    [0] => 0
    [1] => 4
    [2] => 5
    [3] => 9
    [4] => 10
    [5] => 13
    [6] => 15
)
bcdgddfs>
Sign up to request clarification or add additional context in comments.

3 Comments

This example only works on characters who are 1char long, example. Can you fix that?
@Glavić However OP needs to find character positions not strings, but yes I'll.
I was thinking of users that will come here with same problem, so why not support multichar position already.
1

Find all positions, store them in array:

$test = 'abcd.gdda<fsa>dr<second . 111';
$array = array('<','.');
$positions = array();

foreach ($array as $char) {
    $pos = 0;
    while ($pos = strpos($test, $char, $pos)) {
        $positions[$char][] = $pos;
        $pos += strlen($char);
    }
}

print_r($positions);
echo str_replace($array, '', $test);

demo

10 Comments

it looks ok...however .. how can i combine the results so that i have only one array with elements in ascending order not a 2 dimension array?
@SpiderLinked: why would you need that? You can get array of < positions like $positions['<']. If you still wish to have all positions in one array, then you will have to make up a key, that cannot repeat, like char<position> => position or smth like that.
i need that because i need to use those positions easily... my array is made up of 47 elements and i can not use $position[$char][]...for everything...plus ..i need to have all the positions in ascending order..
@SpiderLinked: like I said, then you must create some special keys that can't repeat, like this: demo. If you don't need to know what char is on what position, then that is even easier: demo.
can't i just implode the array and then use str_split?
|
0

Here is one possible solutions, depending on every searching element being a single character.

$array = array(',', '.', '<');
$string = 'fdsg.gsdfh<dsf<g,gsd';

$search = implode($array); $last = 0; $out = ''; $pos = array();
foreach ($array as $char) $pos[$char] = array();

while (($len = strcspn($string, $search)) !== strlen($string)) {
    $last = ($pos[$string[$len]][] = $last + $len) + 1;
    $out .= substr($string, 0, $len);
    $string = substr($string, $len+1);
}
$out.=$string;

Demo: http://codepad.org/WAtDGr7p

Comments

0

EDIT:
PHP has an inbuild function for that

str_replace($array, "", $test);

ORIGINAL ANSWER:
Here is how I would do it:

<?php
$test ='abcd.gdda<fsa>dr';
$array = array('<','.');
foreach($array as $delimiter) {
  // For every delimiter explode the text into array and the recombine it
  $exploded_array = explode($delimiter, $test);
  $test = implode("", $exploded_array);
}
?>

There are faster ways to do it (you will gain some microseconds) but why would you use php if you wanted speed :) I mostly prefer simplicity.

Comments

-1
strtr($str, ['<' => '', '.' => '']);

This will probably outperform anything else, because it doesn't require you to iterate over anything in PHP.

1 Comment

strtr is used to find string not to replace it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.