Похожие чаты

Good, but can you modify your solution so that the

following does not happen?

(1000 iterations of both solutions).

Input:

$paragraph = "o'reilly and peter's dogs and cats";
$junk = ["'s",'/',',','.',';','-'];

Output of my solution:

Array
(
[0] => o'reilly
[1] => and
[2] => peter
[4] => dogs
[6] => cats
)
0.02592 secs

Output of your solution:

Array
(
[0] => o
[1] => reilly
[2] => and
[3] => peter
[4] => s
[5] => dogs
[6] => and
[7] => cats
)
10.00271 secs

In serveral cases your solutions is faster and not in the previous one. However the documentation says:

If you don't need the power of regular expressions, you can choose faster (albeit simpler) alternatives like explode() or str_split().

You must also be careful with: https://stackoverflow.com/questions/15137660/php-preg-split-utf8-characters

Finally, how to eliminate duplicate words with preg_split? I do this for my solution...

$duplicated = [];
$words = array_filter(
explode(' ',
str_replace($junk, ' ',$paragraph)),
function ($item) use (&$duplicated) {
if (trim($item) !== ""
&& !isset($duplicated[$item])) {
$duplicated[$item] = true;
return true;
}
return false;
});

Trim is better for clean chars like \n and performance is not greatly affected. But you can also add \n to $junk.

@being_void_xd

2 ответов

4 просмотра

Why do you ping, when you can just pong

Simply you could give those chars instead of \PL to preg_split. Also that 10 seconds is bulls***. Try it here https://3v4l.org/2u5cd Using preg_split, in this case, is much more faster.

Похожие вопросы

Обсуждают сегодня

А чем вам питонисты не угодили?😂
.
79
всем доброго времени суток! имею вопрос: как понять ТОЧНО, что на нексус производится атака или он перегружен? исходные данные: - Nexus OSS 3.67.1-01 на OrientDB - Total co...
Michael Kostelcev
11
Всем привет, написал код ниже, но он выдает сегфолт, в чем причина? #include <stdio.h> #include <stdlib.h> #include <string.h> struct product { char *name; float price; };...
buzz базз
75
or any website to buy prepaid card with xmr that's not trocador that's down?
Umbrella Party Partner
18
Hi, I can't understand promises in JavaScript and what we should use them for (maybe the teacher didn't teach well XD). Do you have a solution for this? And are promises used...
A
29
Ещё такой вопрос. Мне необходимо хранить пароль пользователя локально. Для этого планирую использовать ini файл. Это для автозаполнения полей логин и пароль при авторизации. Е...
Евгений
19
Добрый день, LO Writer, проблема с нумерацией таблиц (вставка названия). У меня два стиля нумерованных списка, один для основного текста (вида 1.1.1) другой доя приложений (ви...
Виктор
6
My assets the Oceans at Binance, its displaying passive and no automatically convert, this situation will change?
Nationalizze
8
Xem delist ho rha hai agr naa bhechu toh kya hoga after 1 july?
ABHI
27
Ты просто гитлеровскую эстетику плохо понимаешь. Он же всё под Цезаря делал. А это как бы запрещённый приём в политике. Пиджаки они зачем все носят? Чтобы показать что они тип...
Ivan Kropotkin
4
Карта сайта