I want to check preg_match with multiple $line... here is my code
$line = "Hollywood Sex Fantasy , Porn";
if (preg_match("/(Sex|Fantasy|Porn)/i", $line)){
echo 1;}else {echo 2;}
now i want to check in many likes some thing like
$line = "Hollywood Sex Fantasy , Porn";
if (preg_match("/(Sex|Fantasy|Porn)/i", $line, $line1, $line2)){
echo 1;}else {echo 2;}
something like above code with $line1 $line2 $line3
If just one line has to match, you can simply concatenate the lines into a single string:
if (preg_match("/(Sex|Fantasy|Porn)/i", "$line $line1 $line2")) {
echo 1;
} else {
echo 2;
}
This works like an OR condition; match line1 or line2 or line3 => 1.
<?php
//assuming the array keys represent line numbers
$my_array = array('1'=>$line1,'2'=>$line2,'3'=>$line3);
$pattern = '!(Sex|Fantasy|Porn)!i';
$matches = array();
foreach ($my_array as $key=>$value){
if(preg_match($pattern,$value)){
$matches[]=$key;
}
}
print_r($matches);
?>
$lines = array($line1, $line2, $line3);
$flag = false;
foreach($lines as $line){
if (preg_match("/(Sex|Fantasy|Porn)/i", $line)){
$flag = true;
break;
}
}
unset($lines);
if($flag){
echo 1;
} else {
echo 2;
}
?>
You might convert it to a function:
function x(){
$args = func_get_args();
if(count($args) < 2)return false;
$regex = array_shift($args);
foreach($args as $line){
if(preg_match($regex, $line)){
return true;
}
}
return false;
}
Usage:
x("/(Sex|Fantasy|Porn)/i", $line1, $line2, $line3 /* , ... */);
$line = "Hollywood Sex Fantasy , Porn";
if ((preg_match("/(Sex|Fantasy|Porn)/i", $line) && (preg_match("/(Sex|Fantasy|Porn)/i", $line1) && (preg_match("/(Sex|Fantasy|Porn)/i", $line2))
{
echo 1;
}
else
{
echo 2;
}
Crazy example. Using preg_replace instead of preg_match :^ )
$lines = array($line1, $line2, $line3);
preg_replace('/(Sex|Fantasy|Porn)/i', 'nevermind', $lines, -1, $count);
echo $count ? 1 : 2;
Related
I want to count the number of occurrences of each character in a string and print the ones that occur at least Y times.
Example :
Examples func(X: string, Y: int):
func("UserGems",2) => ["s" => 2, "e" => 2]
func("UserGems",3) => []
This what I could achieve so far:
$str = "PHP is pretty fun!!";
$strArray = count_chars($str, 1);
$num = 1;
foreach ($strArray as $key => $value) {
if ($value = $num) {
echo "The character <b>'".chr($key)."'</b> was found $value time(s)
<br>";
}
}
Firstly, you need to list all letters count with separately and to calculate it. Also, you need to calculate elements equal to count which is your find. I wrote 3 types it for your:
<?php
function check($string,$count) {
$achives = [];
$strings = [];
$strArray = count_chars($string, 1);
if($count) {
foreach($strArray as $char => $cnt) {
if($cnt==$count) {
$achives[chr($char)] = $cnt;
}
}
}
return $achives;
}
echo '<pre>';
print_r(check("aa we are all theere Tural a1",1));
So, it is very short version
function check($string,$count = 1) {
$achives = [];
$strArray = count_chars($string, 1);
array_walk($strArray,function($cnt,$letter) use (&$achives,$count){
$cnt!==$count?:$achives[chr($letter)] = $cnt;
});
return $achives;
}
echo '<pre>';
print_r(check("aa we are all theere Tural a1",3));
But it is exactly answer for your question:
<?php
function check($string,$count) {
$achives = [];
$strings = [];
$strArray = str_split($string, 1);
foreach($strArray as $index => $char ){
$strings[$char] = isset($strings[$char])?++$strings[$char]:1;
}
if($count) {
foreach($strings as $char => $cnt) {
if($cnt==$count) {
$achives[$char] = $cnt;
}
}
}
return $achives;
}
<?php
function check($string,$count) {
$achives = [];
$strings = [];
$strArray = count_chars($string, 1);
if($count) {
foreach($strArray as $char => $cnt) {
if($cnt==$count) {
$achives[chr($char)] = $cnt;
}
}
}
return $achives;
}
echo '<pre>';
print_r(check("aa we are all theere Tural a1",1));
You can simply do this with php str_split() and array_count_values() built in functions. i.e.
$chars = str_split("Hello, World!");
$letterCountArray = array_count_values($chars);
foreach ($letterCountArray as $key => $value) {
echo "The character <b>'".$key."'</b> was found $value time(s)\n";
}
Output
If I have the array:
$os = array("Mac", "NT", "Irix", "Linux");
I know that in_array() is what to use if I want to find "Mac" inside $os.
But what I have the array:
$os = array( [1] => "Mac/OSX", [2] => "PC/Windows" );
and I want to see if "Mac" is contained in $os?
Try:
$example = array("Mac/OSX","PC/Windows" );
$searchword = 'Mac';
$matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", $var); });
You could also use array_map to do this. Take a look at the following code:
$array = array(
'Mac/OSX',
'PC/Windows',
);
$result = in_array(true, array_map(function ($word, $match, $char = "/") {
$words = explode('/', $word);
return in_array($match, $words) ? true : false;
}, $array, array('Mac')));
var_dump($result); // bool(true)
You can try this-
$os = array( "Mac/OSX", "PC/Windows" );
function findInArray($os){
foreach($os as $val){
if(strpos($val, $word_to_search) !== false){
return true;
}
}
return false;
}
Here is another solution:
array_map(function($v){
if (strpos($v, 'Mac') !== false) {
echo 'found';
exit;
}
},$os);
echo "Not found";
DEMO
You can simply use preg_grep function of PHP like as
$os = array( '1' => "Mac/OSX", '2' => "PC/Windows" );
print_R(preg_grep("/Mac/",$os));
Output:
Array ( [1] => Mac/OSX )
By using foreach and strpos
$os =array("Mac/OSX","PC/Windows" );
$string = "Mac";
foreach ($os as $data) {
//echo $data;
if (strpos($data,$string ) !== FALSE) {
echo "Match found";
}else{
echo "not found";
}
}
DEMO
function FindString($string, $os)
{
// put the string in between //
$preg = "/$string/";
// Match found
$found = false;
// loop each value
for($j = 0; $j < count($os); $j++)
{
// check with pattern
if(preg_match($preg,$os[$j]))
{
// set var to ture
$found = true;
// Break
break;
}
}
if($found == false)
{
die("Unable to found the string $string.");
}
echo "String $string found in array index $j and value is $os[$j]";
}
$where =array("Mac/OSX","PC/Windows" );
$what = "Mac";
FindString($what, $where);
I have multiple lines like this in a file:
Platform
value: router
Native VLAN
value: 00 01
How can I use PHP to find 'Platform' and return the value 'router'
Currently I am trying the following:
$file = /path/to/file
$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$value.*\$/m";
if(preg_match_all($pattern, $contents, $matches)){
echo "Found Data:\n";
echo implode("\n", $matches[0]);
}
else{
echo "No Data to look over";
}
Heres another simple solution
<?php
$file = 'data.txt';
$contents = file($file, FILE_IGNORE_NEW_LINES);
$find = 'Platform';
if (false !== $key = array_search($find, $contents)) {
echo 'FOUND: '.$find."<br>VALUE: ".$contents[$key+1];
} else {
echo "No match found";
}
?>
returns
Here is a really simple solution with explode.
Hope it helps.
function getValue($needle, $string){
$array = explode("\n", $string);
$i = 0;
$nextIsReturn = false;
foreach ($array as $value) {
if($i%2 == 0){
if($value == $needle){
$nextIsReturn = true;
}
}else{
// It's a value
$line = explode(':', $value);
if($nextIsReturn){
return $line[1];
}
}
$i++;
}
return null;
}
$test = 'Platform
value: router
Native VLAN
value: 00 01 ';
echo getValue('Platform', $test);
If the trailing spaces are a problem for you, you can use trim function.
I am trying to output any array to a directory list format.
A-Z is working, but I want to output words that don't begin with A-Z to the symbol #.
E.G. 1234, #qwerty, !qwerty, etc should be sorted to the # group.
<?php
$aTest = array('apple', 'pineapple', 'banana', 'kiwi', 'pear', 'strawberry', '1234', '#qwerty', '!qwerty');
$range = range('A','Z');
$range[] = "#";
$output = array();
foreach($range AS $letters){
foreach($aTest AS $fruit){
if(ucfirst($fruit[0]) == $letters){
$output[$letters][] = ucfirst($fruit);
}
}
}
foreach($output AS $letter => $fruits){
echo $letter . "<br/>--------<br/>\n";
sort($fruits);
foreach($fruits AS $indFruit){
echo $indFruit . "<br/>\n";
}
echo "<br/>\n";
}
?>
$output['#'] = array();
foreach($range as $letter){
$output[$letter] = array();
}
foreach($aTest AS $fruit){
$uc = ucfirst($fruit);
if(array_search($uc[0], $range) === FALSE){
$output['#'][] = $uc;
} else {
$output[$uc[0]][] = $uc;
}
}
notice that I have removed outer loop, as you don't need it
You should reverse the order of the two foreach loops, use break and a temporary variable:
foreach($aTest as $fruit){
$temp = 1;
foreach($range as $letters){
if(ucfirst($fruit[0]) == $letters){
$output[$letters][] = ucfirst($fruit);
$temp = 0;
break;
}
}
if($temp){
$output["#"][] = $fruit;
}
}
ksort($output);
To avoid these complications, you may use only one foreach loop and the built-in PHP function in_array:
foreach($aTest as $fruit){
$first = ucfirst($fruit[0]);
if(in_array($first, $range)){
$output[$first][] = ucfirst($fruit);
}
else{
$output["#"][] = $fruit;
}
}
ksort($output);
I would categorize them first using ctype_alpha() and then sorting the result by the array key:
$output = array();
foreach ($aTest as $word) {
$output[ctype_alpha($word[0]) ? strtoupper($word[0]) : '#'][] = $word;
}
ksort($output);
I use php preg_match to match the first & last word in a variable with a given first & last specific words,
example:
$first_word = 't'; // I want to force 'this'
$last_word = 'ne'; // I want to force 'done'
$str = 'this function can be done';
if(preg_match('/^' . $first_word . '(.*)' . $last_word .'$/' , $str))
{
echo 'true';
}
But the problem is i want to force match the whole word at (starting & ending) not the first or last characters.
Using \b as boudary word limit in search:
$first_word = 't'; // I want to force 'this'
$last_word = 'ne'; // I want to force 'done'
$str = 'this function can be done';
if(preg_match('/^' . $first_word . '\b(.*)\b' . $last_word .'$/' , $str))
{
echo 'true';
}
I would go about this in a slightly different way:
$firstword = 't';
$lastword = 'ne';
$string = 'this function can be done';
$words = explode(' ', $string);
if (preg_match("/^{$firstword}/i", reset($words)) && preg_match("/{$lastword}$/i", end($words)))
{
echo 'true';
}
==========================================
Here's another way to achieve the same thing
$firstword = 'this';
$lastword = 'done';
$string = 'this can be done';
$words = explode(' ', $string);
if (reset($words) === $firstword && end($words) === $lastword)
{
echo 'true';
}
This is always going to echo true, because we know the firstword and lastword are correct, try changing them to something else and it will not echo true.
I wrote a function to get Start of sentence but it is not any regex in it.
You can write for end like this. I don't add function for the end because of its long...
<?php
function StartSearch($start, $sentence)
{
$data = explode(" ", $sentence);
$flag = false;
$ret = array();
foreach ($data as $val)
{
for($i = 0, $j = 0;$i < strlen($val), $j < strlen($start);$i++)
{
if ($i == 0 && $val{$i} != $start{$j})
break;
if ($flag && $val{$i} != $start{$j})
break;
if ($val{$i} == $start{$j})
{
$flag = true;
$j++;
}
}
if ($j == strlen($start))
{
$ret[] = $val;
}
}
return $ret;
}
print_r(StartSearch("th", $str));
?>