php search on string comma separated and get element that match - php

I have a question, if anyone can help me to solve this. I have a string separated by commas, and I want to find an item that partially matches:
$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
I need to get only the full string from partial match as a result of filter:
$result = "GenomaPrintOrder";

With preg_match_all you can do like this.
Php Code
<?php
$subject = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView, NewPrintOrder";
$pattern = '/\b([^,]*PrintOrder[^,]*)\b/';
preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);
foreach ($matches as $val) {
echo "Matched: " . $val[1]. "\n";
}
?>
Output
Matched: GenomaPrintOrder
Matched: NewPrintOrder
Ideone Demo

$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
$result = array();
$tmp = explode(",", $string);
foreach($tmp as $entrie){
if(strpos($entrie, $string) !== false)
$result[] = trim($entrie);
}
This will get you an array with all strings that match your search-string.

You can use regular expression to get the result:
$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
$regex = '/([^,]*' . preg_quote($search, '/') . '[^,]*)/';
preg_match($regex, $string, $match);
$result = trim($match[1]); // $result == 'GenomaPrintOrder'

$search = "PrintOrder";
$string = "IDperson, Inscription, GenomaPrintOrder, GenomaPrintView";
$array = explode(" ", $string);
echo array_filter($array, function($var) use ($search) { return preg_match("/\b$searchword\b/i", $var); });

Since there are so many different answers already, here is another:
$result = preg_grep("/$search/", explode(", ", $string));
print_r($result);

Related

What's wrong with preg_match_all and my string?

I have a series of tag in the text that I want to match with preg_match_all but the $regex string has something wrong and I can't understand what to do.
$tagReplace = ['mov', 'flv', 'youtube'];
foreach ($tagReplace as $plg_tag) {
$regex = "#{" . $plg_tag . "}(.*?){/" . $plg_tag . "}#s";
$var = preg_match_all($regex, "{mov}the_video_url{/mov}", $matches, PREG_PATTERN_ORDER);
var_dump($matches);
}
<?php
$matches = array();
$p = '/(mov|flv|youtube)/';
$replace_to = 'your text you want to be insted of the mov or flv or youtube';
$str = ' the string that you want to work on and replace its content';
$p_c = array(
$p => function($match) {
$ret = str_replace("mov", $replace_to, $match[0]);
$ret = str_replace("flv", $replace_to, $ret);
$ret = str_replace("youtube", $replace_to, $ret);
return $ret;
}
);
$res3 = preg_replace_callback_array($p_c, $str);

How to echo explode array?

EDIT: More clear: I want to echo $data as an array.
I have this:
$lic = $_GET['lic'];
$locationtodb = '../../files/';
$licenses = $locationtodb.'filea.txt';
$SearchLicense = $lic;
$pattern = preg_quote($SearchLicense, '/');
$pattern = "/^.*$pattern.*\$/m";
preg_match_all($pattern, $licenses, $matches);
$wholeLine = implode("\n", $matches[0]);
$data = explode(":", $wholeLine);
I can use somethings like this to replace strings:
$CurrentLine = $lic.':'.'active'.':'.$data[2];
$NewLine = $lic.':'.'suspended'.':'.$data[2];
$new_contents = file_get_contents($licenses);
$new_contents = str_replace($CurrentLine,$NewLine,$new_contents);
file_put_contents($licenses,$new_contents);
And it does work !
But if I typed something like:
echo $data[2];
It give nothing ...
Why?
Thanks.
Solution discovered!
$licenses = $locationtodb.'filea.txt';
Must be:
$licenses = file_get_contents($locationtodb.'filea.txt');

replace all occurrences after nth occurrence php?

I have this string...
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|"
How do I replace all the occurrences of | with " " after the 8th occurrence of | from the beginning of the string?
I need it look like this, 1|2|1400|34|A|309|Frank|william|This is the line here
$find = "|";
$replace = " ";
I tried
$text = preg_replace(strrev("/$find/"),strrev($replace),strrev($text),8);
but its not working out so well. If you have an idea please help!
You can use:
$text = '1|2|1400|34|A|309|Frank|william|This|is|the|line|here|';
$repl = preg_replace('/^([^|]*\|){8}(*SKIP)(*F)|\|/', ' ', $text);
//=> 1|2|1400|34|A|309|Frank|william|This is the line here
RegEx Demo
Approach is to match and ignore first 8 occurrences of | using ^([^|]*\|){8}(*SKIP)(*F) and the replace each | by space.
You can use explode()
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|";
$arr = explode('|', $text);
$result = '';
foreach($arr as $k=>$v){
if($k == 0) $result .= $v;
else $result .= ($k > 7) ? ' '.$v : '|'.$v;
}
echo $result;
You could use the below regex also and replace the matched | with a single space.
$text = '1|2|1400|34|A|309|Frank|william|This|is|the|line|here|';
$repl = preg_replace('~(?:^(?:[^|]*\|){8}|(?<!^)\G)[^|\n]*\K\|~', ' ', $text);
DEMO
<?php
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|";
$texts = explode( "|", $text );
$new_text = '';
$total_words = count( $texts );
for ( $i = 0; $i < $total_words; $i++)
{
$new_text .= $texts[$i];
if ( $i <= 7 )
$new_text .= "|";
else
$new_text .= " ";
}
echo $new_text;
?>
The way to do that is:
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|";
$arr = explode('|', $text, 9);
$arr[8] = strtr($arr[8], array('|'=>' '));
$result = implode('|', $arr);
echo $result;
Example without regex:
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|";
$array = str_replace( '|', ' ', explode( '|', $text, 9 ) );
$text = implode( '|', $array );
str_replace:
If subject is an array, then the search and replace is performed with
every entry of subject, and the return value is an array as well.
explode:
If limit is set and positive, the returned array will contain a
maximum of limit elements with the last element containing the rest of
string.

Remove word from a string

I have a csv file that contains company names. I would want to match it against my database. In order to have a cleaner and nearer matches, I am thinking of eliminating some company suffixes like 'inc', ' inc', ', inc.' or ', inc'. Here's my sample code:
$string = 'Inc Incorporated inc.';
$wordlist = array("Inc","inc."," Inc.",", Inc.",", Inc"," Inc");
foreach ($wordlist as &$word) {
$word = '/\b' . preg_quote($word, '/') . '\b/';
}
$string = preg_replace($wordlist, '', $string);
$foo = preg_replace('/\s+/', ' ', $string);
echo $foo;
My problem here is that the 'inc.' doesn't get removed. I'm guessing it has something to do with the preq_quote. But I just can't figure out how to solve this.
Try this :
$string = 'Inc incorporated inc.';
$wordlist = array("Inc","inc.");
foreach ($wordlist as $word) {
$string =str_replace($word, '', $string);
}
echo $string;
OR
$string = 'Inc Incorporated inc.';
$wordlist = array("Inc","inc.");
$string = str_replace($wordlist, '', $string);
echo $string;
This will output as 'corporated'...
If you want "Incorporated" as result, make the "I" is small.. and than run my above code (first one)...
Try this. It may involve type juggling at some point, but will have your desired result
$string = 'Inc Incorporated inc.';
$wordlist = array('Inc', 'inc.');
$string_array = explode(' ', $string);
foreach($string_array as $k => $a) {
foreach($wordlist as $b) {
if($b == $a){
unset($string_array[$k]);
}
}
$string_array = implode('', $string_array);
You can use this
$string = 'Inc Incorporated inc.';
$wordlist = array("Inc "," inc.");
$foo = str_replace($wordlist, '', $string);
echo $foo;
Run this code here
This will work for any number of elements in array...
$string = 'Inc Incorporated inc.';
$wordlist = array("Inc");
foreach($wordlist as $stripped)
$string = preg_replace("/\b". preg_quote($stripped,'/') ."(\.|\b)/i", " ", $string) ;
$foo = preg_replace('/\s+/', ' ', $string);
echo $foo;

PHP and regex Task

I have a string in php formatted like this:
http://aaaaaaaaaa/*http://bbbbbbbbbbbbbbb
where aaa... and bbb.... represent random characters and are random in length.
I would like to parse the string so that I am left with this:
http://bbbbbbbbbbbbbbb
In this case I wouldn't recommend regex but a simple substring or explode
$data = "http://aaaaaaaaaa/*http://bbbbbbbbbbb"
$parts = explode('*', $data);
echo $parts[1];
fin :)
You don't need regular expressions at all in this case:
$str = 'http://aaaaaaaaaa/*http://bbbbbbbbbbbbbbb';
echo substr($str, strpos($str, 'http://', 1));
Hi This would help you to get the address:
$str = 'http://www.example.com/*http://www.another.org/';
$pattern = '/^http:\/\/[\.\w\-]+\/\*(http:\/\/.+)$/';
//$result = preg_replace($pattern, '$1', $str);
$found = preg_match_all($pattern, $str, $result);
$url = (!$found==0) ? $result[1][0] : '';
echo $str . '<br />' . $url;
Here is the regular expression way:
$str = 'http://aaaaaaaaaa/*http://bbbbbbbbbbbbbbb';
$url = preg_replace("/^.*(http:\/\/.*[^(http:\/\/)+])$/", "$1", $str);
echo $url;
Here is a clean solution: grab everything after the last occurrence of "http://".
$start = strrpos($input, 'http://');
$output = substr($input, $start);

Categories