I am trying to get specified words out of an string.
I do not know if I forgot something but it only prints the first two values? Can someone help me with that?
Thanks for the help!
$orgData["connector"] = 'some stringy thing SMA-female N-female FME-female';
if (preg_match_all('/(N-female|SMA-female|FME-female)/',$orgData["connector"], $matches)) {
foreach ($matches as $i => $match) {
if ($match[$i] == "N-female") {
$con1 = "|Connector: N-female";
}
if ($match[$i] == "SMA-female") {
$con2 = "|Connector: SMA-female";
}
if ($match[$i] == "FME-female") {
$con3 = "|Connector: FME-female";
}
print_r($con1 . $con2 . $con3);
}
}
You may use a single variable and just append the matches once found:
$orgData = 'some stringy thing SMA-female N-female FME-female';
$con = "";
if (preg_match_all('/(?:N|SMA|FME)-female/', $orgData, $matches)) {
foreach ($matches[0] as $match) {
if ($match == "N-female") {
$con .= "|Connector: N-female";
}
if ($match == "SMA-female") {
$con .= "|Connector: SMA-female";
}
if ($match == "FME-female") {
$con .= "|Connector: FME-female";
}
}
}
echo $con; // => |Connector: SMA-female|Connector: N-female|Connector: FME-female
See the PHP demo.
Note I sharnk the pattern a bit: (?:N|SMA|FME)-female matches N, SMA or FME and then -female.
Related
Hi everyone i have faced a problem during my working to return a response for a api
the main problem is
$name = "تش";
$restaurants = [
"تشك تشيكن",
"بيتزا ساخنة",
"كينتاكي",
"تشيكن سبوت"
];
foreach ($restaurants as $restaurant) {
if (strpos($restaurant, $name)) {
echo "founded";
}
}
any help ?
Your first argument should be $item and then the keyword you are searching for which is $search
So your code should look like:
$item = "أهلا وسهلا بكم";
$search = "وسهلا";
if (strpos($item, $search)){
echo "founded";
}else {
echo "not founded";
}
The first argument in strpos should be the haystack, which is the string you want to search in, and the second argument is the needle, which is the string you want to search for
<?php
$item = "أهلا وسهلا بكم";
$search = "وسهلا";
// look if $search is in $item
if (strpos($item, $search)){
echo "founded";
}else {
echo "not founded";
}
https://3v4l.org/C07o8
based on this duplicate, Arabic characters are encoded using multibyte characters, so you need to use grapheme_strpos()
if (function_exists('grapheme_strpos')) {
$pos = grapheme_strpos($tweet, $keyword);
} elseif (function_exists('mb_strpos')) {
$pos = mb_strpos($tweet, $keyword);
} else {
$pos = strpos($tweet, $keyword);
}
I have found the answer finally
$name = "تش";
$restaurants = [
"تشك تشيكن",
"بيتزا ساخنة",
"كينتاكي",
"تشيكن سبوت"
];
foreach ($restaurants as $restaurant) {
if (strpos($restaurant, $name) !== false) {
echo "founded";
}
}
This question was asked in a recent job interview I gave and I was unable to answer it. Here is the question:
From a given email list (johndoe#noemail.com, xyz#no-email.com, noemail#xyz.com, answers#no email.com, jpt#nooooemail.com, kondoe#nomail.com) extract only those emails ending with (#noemail.com, #no-email.com, and #no email.com).
I searched and tried to run the code but it didn't ran.
<?php
$email_list = (johndoe#noemail.com, xyz#no-email.com, noemail#xyz.com, answers#no email.com, jpt#nooooemail.com, kondoe#nomail.com);
$pattern = ('#noemail.com', '#no-email.com', '#no email.com' );
echo preg_match($pattern, $email_list);
?>
$email_list = array('johndoe#noemail.com', 'xyz#no-email.com',
'noemail#xyz.com', 'answers#no email.com',
'jpt#nooooemail.com', 'kondoe#nomail.com');
$result = array();
foreach ($email_list as $email) {
if (preg_match('~#no[ -]?email\.com~', $email)) {
$result[] = $email;
}
}
var_export($result);
// output ->
// array (
// 0 => 'johndoe#noemail.com',
// 1 => 'xyz#no-email.com',
// 2 => 'answers#no email.com',
// )
<?php
$email_list = array("johndoe#noemail.com", "xyz#no-email.com", "noemail#xyz.com", "answers#no email.com", "jpt#nooooemail.com", "kondoe#nomail.com");
$matchlist = array("#noemail.com", "#no-email.com", "#no email.com");
function str_contains($haystack, $needle) {
return (strpos($haystack, $needle) !== false);
}
foreach ($email_list as $email) {
foreach($matchlist as $match) {
if (str_contains($email, $match)) {
echo $email . "<br>";
break;
}
}
}
Not the perfect way, but works.
I am developing a system that searches for words that the user types in php files, using PHP without MySQL but I am having a problem. The system works really well when there is not a line break in the file. For example, if I search for the word "good" in a file that contains the text "good morning" works fine, but if I search for "good" in a file that contains the text "goodmorning" (with a line break) it won't list the file as a result. Here is my code:
index.php
<form action="busca.php" method="get">
<input type="text" name="s"><br>
<input type="submit">
</form>
busca.php
<?php
$pesq = (isset($_GET['s'])) ? trim($_GET['s']) : '';
if (empty($pesq)) {
echo 'Type something.';
} else {
$index = "index.php";
$busca = glob("posts/content/*.php", GLOB_BRACE);
$lendo = "";
$conteudo = "";
foreach ($busca as $item) {
if ($item !== $index) {
$abrir = fopen($item, "r");
while (!feof($abrir)) {
$lendo = fgets($abrir);
$conteudo .= $lendo;
$lendo .= strip_tags($lendo);
}
if (stristr($lendo, $pesq) == true) {
$dados = str_replace(".php", "", $item);
$dados = basename($dados);
$result[] = "$dados";
unset($dados);
}
fclose($abrir);
}
}
if (isset($result) && count($result) > 0) {
$result = array_unique($result);
echo '<ul>';
foreach ($result as $link) {
echo "<li>$link</li>";
}
echo '</ul>';
} else {
echo 'No results';
}
}
?>
Your usage of stristr is incorrect.
Compare it with false like this:
if (stristr($lendo, $pesq) !== false) {
If a string is located — the function returns the substring. Which can be casted as boolean true or false, you never know. If it doesn't find it — it returns false — the only correct value you should compare it to.
Even better to use strpos for this.
My variant:
foreach ($busca as $item) {
if ($item !== $index) {
$lendo = file_get_contents($item);
$lendo = strip_tags($lendo);
if (strpos($lendo, $pesq) !== false) {
$dados = str_replace(".php", "", basename($item));
$result[] = "$dados";
}
}
}
To fix the linebreaks - try to get rid of them
Like this:
$lendo = file_get_contents($item);
$lendo = strip_tags($lendo);
$lendo = str_replace(["\r","\n"], ' ', $lendo);
I am currently using this:
if(strtolower(substr($subject,0,3)) != 're:' and strtolower(substr($subject,0,3)) != 'fw:' and strtolower(substr($subject,0,1)) != '#' and strtolower(substr($subject,0,5)) != 'read:') {
to check if the first characters of the $subject variable are not equal to,
re:
fw:
#
read:
in uppercase or lowercase, how can i check exactly the same thing but by using items contained in an array instead?
like:
$array = array("re:", "fw:", "#", "read:");
foreach (array('re:', 'fw:', '#', 'read:') as $keyword) {
if (stripos($subject, $keyword) === 0) {
echo 'found!';
break;
}
}
or
$found = array_reduce(array('re:', 'fw:', '#', 'read:'), function ($found, $keyword) use ($subject) {
return $found || stripos($subject, $keyword) === 0;
});
or
if (preg_match('/^(re:|fw:|#|read:)/i', $subject)) {
echo 'found!';
}
or
$keywords = array('re:', 'fw:', '#', 'read:');
$regex = sprintf('/^(%s)/i', join('|', array_map('preg_quote', $keywords)));
if (preg_match($regex, $subject)) {
echo 'found!';
}
You can wrap the functionality of matching a string against a set of prefixes in a function:
function matches_prefixes($string, $prefixes)
{
foreach ($prefixes as $prefix) {
if (strncasecmp($string, $prefix, strlen($prefix)) == 0) {
return true;
}
}
return false;
}
And use like this:
if (!matches_prefixes($subject, ['re:', 'fw:', '#', 'read:'])) {
// do stuff
}
See also: strncasecmp
What I'm trying to is search my string to see if there is any of the following arrays there
if not then we need to add .com to end of it.
$kwlines is my string and i have set it to test but this is what I get
test.comtest.com.comtest.com.com.comtest.com.com.com.comtest.com.com.com.com.comtest.com.com.com.com.com.comtest.com.com.com.com.com.com.com
foreach ($kwlines as $kw) {
$owned_urls= array('.com', '.co.uk', '.net','.org', '.gov','.gov.co.uk','.us');
foreach ($owned_urls as $url) {
if (strpos($kw, $url) !== TRUE) {
$kw .= ".com";
echo "$kw";
}
}
Could you please help me understand what I do wrong?
Thank you
try this:
foreach ($kwlines as $kw) {
$owned_urls= array('.com', '.co.uk', '.net','.org', '.gov','.gov.co.uk','.us');
foreach ($owned_urls as $url) {
$find = 0;
if (strpos($kw, $url) !== TRUE) {
$find = 1;
}
}
if($find == 1)
$kw .= ".com";
echo "$kw";
}
foreach ($owned_urls as $url) {
if (strpos($kw, $url) !== TRUE) {
$kw .= ".com";
echo "$kw";
exit();
}
}
Your code is running for each TLD in that array. Pull it out of the array...once the tld is found, it exists the foreach loop in my example above.