Preg_match_all играчка с масиви

Ticketa

Registered
В момента ползвам следния код, който работи безусловно добре:

Код:
$search = 'title|title2|title3';
if ( preg_match_all('/^'.$search .'/im', $content, $matches, PREG_SET_ORDER) ) {
	echo "Открито в ID: " . $ID . "<br /> намерени изрази:<ul>";
	foreach ( $matches as $means ) {
            echo "<li>" . $means[0] . "</li>";
        }
	echo "</ul>";
}


output:
Открито в ID: 15
намерени изрази:
title3
title2

Открито в ID: 18
намерени изрази:
title

Обаче искам да го направя, чрез array за search и да добавя дескрипшън:
Код:
$search = array ( 
	array('title', 'neshto'), 
	array('title2', 'description2'), 
	array('title3', 'description3'), 
);

със следния изход:


output:
Открито в ID: 15
намерени изрази:
title3 >>>> description3
title2 >>>> description2

Открито в ID: 18
намерени изрази:
title >>>> neshto2

За момента единственото ми решение, което открих е да ползвам foreach преди
Код:
 if ( preg_match_all('/^'.$search .'/im', $content, $matches, PREG_SET_ORDER) ) {
и съответно (логично) е разултата ми да бъде:


Открито в ID: 15
намерени изрази:
title3 >>>> description3

Открито в ID: 15
намерени изрази:

title2 >>>> description2

Открито в ID: 18
намерени изрази:
title >>>> neshto2

Опитах да ползвам preg_grep, обаче не подкарах нещата. Последния вариант, който ми остава е да ползвам strpos.

Някакви идеи дали има как да ползвам preg_match_all ?
 
Я дай по-голяма част от кода. Какво е цалостната "реална" идея? И кое от къде идва. Предполагам, че нещата идват от база данни, а ти показваш само примерен процедурен PHP код. Според крайната цел може да има и по-добро решение.
 
Revelation каза:
Я дай по-голяма част от кода. Какво е цалостната "реална" идея? И кое от къде идва. Предполагам, че нещата идват от база данни, а ти показваш само примерен процедурен PHP код. Според крайната цел може да има и по-добро решение.

Не в момента не използвам база от данни, а си правя експерименти (уча се и тествам как да работя още по-добре) с масиви и RegEx.

В случая:
$content съдържа някакъв текст.

пример:

<?php
$ID = 1;
$content = "title3 Lorem Ipsum is simply dummy text title of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer title took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing title2 software like Aldus PageMaker including versions of Lorem Ipsum. title3";

$search = 'title|title2|title3';
if ( preg_match_all('/^'.$search.'/im', $content, $matches, PREG_SET_ORDER) ) {
echo "Открито в ID: " . $ID . "<br /> намерени изрази:<ul>";
foreach ( $matches as $means ) {
echo "<li>" . $means[0] . "</li>";
}
echo "</ul>";
}

Резултат:
Код:
Открито в ID: 1<br /> 
намерени изрази:
<ul>
	<li>title</li>
	<li>title2</li>
	<li>title3</li>
</ul>

П.С. Между другото има някакъв бъг защото в текства имам 4 израза за откриване, а то открива 3 (изпуска първия title3)

ЕДИТ:
Опитах и по следния начин, но не го подкарах (може би заради multidimensional масив):

Код:
<?php
$ID = 1;
$content = "title3 Lorem Ipsum is simply dummy text title of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer title took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing title2 software like Aldus PageMaker including versions of Lorem Ipsum. title3";

$search = array ( 
	array('title', 'neshto'), 
	array('title2', 'description2'), 
	array('title3', 'description3'), 
);
$RegEx = array_filter($search, function ($v) USE ($content) {
	return preg_match_all('/^'.$v[0].'/im', $content, $matches, PREG_SET_ORDER);
});
if ( $RegEx ) {
	echo "Открито в ID: " . $ID . "<br /> намерени изрази:<ul>";
	foreach ( $matches as $means ) {
            echo "<li>" . $means[0] . "</li>";
        }
	echo "</ul>";
}
 
Открих къде бъркам, това е работещо решение:
Код:
<?php
$ID = 1;
$content = "titlez Lorem Lorem Lorem LoremLoremLoremLoremLoremLoremLorem Lorem Ipsum is simply dummy text title of the printing and typesetting c99 asd industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer title took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing title2 software like Aldus PageMaker including versions of Lorem Ipsum. title3";

$search = array (
    array('title', 'neshto'),
    array('text', 'description2'),
    array('Lorem', 'description3'),
);
$matches = array_filter($search, function ($v) USE ($content) {
    return preg_match_all('/'.$v[0].'/', $content, $matches, PREG_SET_ORDER);
});
if ( $matches ) {
    echo "Открито в ID: " . $ID . "<br /> намерени изрази:<ul>";
    foreach ( $matches as $means ) {
        echo "<li>" . $means[0] . " >>>>>> " . $means[1] . "</li>";
    }
    echo "</ul>";
}
 
PHP:
<?php
$keywordDescriptionMap = [
    'title' => 'neshto',
    'title2' => 'description2',
    'title3' => 'description3',
];

$content = "title3 Lorem Ipsum is simply dummy text title of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer title took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing title2 software like Aldus PageMaker including versions of Lorem Ipsum. title3";
$cleanContent = preg_replace("/[^a-zA-Z0-9\s]/", "", $content);

// Ако искаш да е case-insensitive
// $cleanContent = strtolower($cleanContent);

$wordsList = explode(" ", $cleanContent);

$foundKeywords = array_intersect(array_keys($keywordDescriptionMap), $wordsList);

foreach ($foundKeywords as $keyword) {
    echo "Keyword: {$keyword}; Description: $keywordDescriptionMap[$keyword]" . PHP_EOL;
}

Изход:
Keyword: title; Description: neshto
Keyword: title2; Description: description2
Keyword: title3; Description: description3
 
Изникна ми един дребен проблем, за който не се сещам как да го реша (ползвам моя пример от кода по-горе)

Код:
$RegExMatches = array_filter($Patterns, function ($var) use ($content) {
       return preg_match_all('#' . $var[0] . '#isS', $content, $matches, PREG_OFFSET_CAPTURE);
});
if ( $RegExMatches ) {
      //code
}

Кода бачка така както искам с единствената разлика, че не мога да ползвам $matches някаква идея как да го добавя като двоен return? (пробвах да добавя

$content променливата
Код:
$content = file_get_contents("$path/$file")
вземам информацията за даден файл.

Обаче не ми върши работа по този нелеп начин.
Код:
$RegExMatches = array_filter($Patterns, function ($var) use ($content) {
if ( $RegExMatches = preg_match_all('#' . $var[0] . '#isS', $content, $matches, PREG_OFFSET_CAPTURE) ) {
       return array($RegExMatches, $matches[0]);
}
});

=================

Код:
preg_match_all('/(foo)(bar)(baz)/', 'foobarbaz', $matches, PREG_OFFSET_CAPTURE);
print_r($matches);

Този параметър, който идва от matches конкретно ми трябва да ползване:
Array
(
[0] => Array
(
[0] => Array
(
[0] => foobarbaz
[1] => 0
)

)

[1] => Array
(
[0] => Array
(
[0] => foo
[1] => 0
)

)

[2] => Array
(
[0] => Array
(
[0] => bar
[1] => 3
)

)

[3] => Array
(
[0] => Array
(
[0] => baz
[1] => 6
)

)

)
 
Yikes...

Това с цел да научиш regex-и ли е, защото подхода ти е меко казано ужасен и объркващ.

Анонимната функция на array_filter() трябва да връща boolean. Не можеш да върнеш резултата. В този случай, масива, който ти връща array_filter() трябва да го минеш след това през array_map() и да върнеш $matches, но тогава ще забележиш защо го казах това от горния параграф.
 
Revelation каза:
Yikes...

Това с цел да научиш regex-и ли е, защото подхода ти е меко казано ужасен и объркващ.

Правя си безсмислени експерименти :D


Анонимната функция на array_filter() трябва да връща boolean. Не можеш да върнеш резултата. В този случай, масива, който ти връща array_filter() трябва да го минеш след това през array_map() и да върнеш $matches, но тогава ще забележиш защо го казах това от горния параграф
. :violin: :music-guitarred: :eek:bscene-drinkingdrunk:
 

Горе