PHP Check string contain #(any) [duplicate] - php

I have a string that has hash tags in it and I'm trying to pull the tags out I think i'm pretty close but getting a multi-dimensional array with the same results
$string = "this is #a string with #some sweet #hash tags";
preg_match_all('/(?!\b)(#\w+\b)/',$string,$matches);
print_r($matches);
which yields
Array (
[0] => Array (
[0] => "#a"
[1] => "#some"
[2] => "#hash"
)
[1] => Array (
[0] => "#a"
[1] => "#some"
[2] => "#hash"
)
)
I just want one array with each word beginning with a hash tag.

this can be done by the /(?<!\w)#\w+/ regx it will work

That's what preg_match_all does. You always get a multidimensional array. [0] is the complete match and [1] the first capture groups result list.
Just access $matches[1] for the desired strings. (Your dump with the depicted extraneous Array ( [0] => Array ( [0] was incorrect. You get one subarray level.)

I think this function will help you:
echo get_hashtags($string);
function get_hashtags($string, $str = 1) {
preg_match_all('/#(\w+)/',$string,$matches);
$i = 0;
if ($str) {
foreach ($matches[1] as $match) {
$count = count($matches[1]);
$keywords .= "$match";
$i++;
if ($count > $i) $keywords .= ", ";
}
} else {
foreach ($matches[1] as $match) {
$keyword[] = $match;
}
$keywords = $keyword;
}
return $keywords;
}

Try:
$string = "this is #a string with #some sweet #hash tags";
preg_match_all('/(?<!\w)#\S+/', $string, $matches);
print_r($matches[0]);
echo("<br><br>");
// Output: Array ( [0] => #a [1] => #some [2] => #hash )

Related

Compare a string and a php array and only show the matches

I have a string that looks like this:
"illustration,drawing,printing"
I have an array that looks like this:
Array (
[0] => illustration
[1] => drawing
[2] => painting
[3] => ceramics
)
How can I compare the two and only display the terms that exist in both the string and array?
So in the above example, I would want to output something that looks like this:
SKILLS: illustration, drawing
Thank you!
use explode(), array_intersect() and implode()
<?php
$string = "illustration,drawing,printing";
$array = Array (
0 => 'illustration',
1 => 'drawing',
2 => 'painting',
3 => 'ceramics'
);
$stringArray = explode(',',$string);
$common = array_intersect($stringArray,$array);
echo "Skills :".implode(',',$common);
https://3v4l.org/StqYN
You can do something like this:
Function:
function functionName($string, $array){
$skills = '';
// Create a temp array from your string breaking appart from the commas
$temparr = explode(",", $string);
// Iterate through each of the words now
foreach($temparr as $str){
// Check to see if our current string is in the array provided
if(in_array($str, $array)){
// If it is, then add it to the string "skills"
$skills .= "${str}, ";
}
}
// Cut the last space and comma off the end of the str.
$skills = substr($skills, 0, strlen($skills) - 2);
// Return our results
return 'SKILLS: '.$skills;
}
Usage:
$string = "illustration,drawing,printing";
$array = Array (
0 => "illustration",
1 => "drawing",
2 => "painting",
3 => "ceramics"
);
// Just input our string and the array we want to search through
echo(functionName($string, $array));
Live Demos:
https://ideone.com/qyqgzo
http://sandbox.onlinephpfunctions.com/code/65dc988370ad8ce61ab5ccbc232af4bcf8bd3d42
You could replace the comma , and join the string words on OR | and grep for them. This will match the word anywhere in each array element:
$result = preg_grep("/".str_replace(",", "|", $string)."/", $array);
If you want exact matches only then: "/^(".str_replace(",", "|", $string).")$/"
Firstly convert that string into array.
use array_intersect();
$str = "illustration,drawing,printing";
$ar1 = explode(",",$str);
print_r ($ar1);
$ar2 = Array ("illustration","drawing","painting","ceramics");
echo "<br>";
print_r ($ar2);
$result = array_intersect($ar1, $ar2);
echo "Skills :".implode(',',$result);
OUTPUT:
Array (
[0] => illustration
[1] => drawing
[2] => printing
)
Array (
[0] => illustration
[1] => drawing
[2] => painting
[3] => ceramics
)
SKILLS: illustration, drawing

How explode string to array elements via regex?

I want to convert nested brackets to array with keywords. Here is pattern:
preg_match_all('/(?=\{((?:[^{}]++|\{(?0)\})++)\})/', $string, $res);
And data which need to parse:
employee {
cashier { salary = 100; }
technician { age = 44; }
}
Result, that I need:
Array
(
[employee] => Array (
[0] => Array
(
[cashier] => Array
(
[salary] => 100
)
)
[1] => Array
(
[technician] => Array
(
[age] => 44
)
)
)
)
But cant iterate within nested brackets. Stucked here. Thanks in advance for your help
You'll need a recursive approach here.
First, analyze the outer structure with { and } on both sides.
See, if we can find another nested structure
If not, look for key = value pairs and return them
A regex demo for the outer structure can be found on regex101.com, a complete PHP demo would look as follows:
<?php
$string = <<<DATA
employee {
cashier { salary = 100; }
technician { age = 44; }
}
DATA;
// regular expressions
$outer = '~(?P<key>\w+)\s*(?P<value>\{(?:[^{}]*|(?R))*\})~';
// inner, key = value
$inner = '~(?P<key>\w+)\s*=\s*(?P<value>\w+)~';
function parse($string) {
global $outer, $inner;
$result = array();
// outer
preg_match_all($outer, $string, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$result[$match["key"]] = parse(
substr($match["value"], 1, -1)
);
}
// if not found, inner structure
if (!$matches) {
preg_match_all($inner, $string, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$result[$match["key"]] = $match["value"];
}
return $result;
}
return $result;
}
$result = parse($string);
print_r($result);
?>
This yields:
Array
(
[employee] => Array
(
[cashier] => Array
(
[salary] => 100
)
[technician] => Array
(
[age] => 44
)
)
)

Display all matches from preg match

How can display all the results instead of just the first match from the preg match?
This is the content of $show:
One
Two
Three
This is the PHP code:
preg_match("/<a href=\"(.+?)\">(.+?)<\/a>/", $show, $display);
$xml = "<name>".$display[2]."</name><link>".$display[1]."</link>";
echo $xml;
The output is:
<name>One</name><link>http://website.com/one</link>
But I want it to display all the results like this:
<name>One</name><link>http://website.com/one</link>
<name>Two</name><link>http://website.com/two</link>
<name>Three</name><link>http://website.com/three</link>
this is the output of print_r($display); ...
Array
(
[0] => Array
(
[0] => One
[1] => Two
[2] => Three
)
[1] => Array
(
[0] => http://website.com/one
[1] => http://website.com/two
[2] => http://website.com/three
)
[2] => Array
(
[0] => One
[1] => Two
[2] => Three
)
)
You would use preg_match_all() to get all matches and then iterate through them:
preg_match_all('~(.+?)~s', $html, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
echo "<name>".$m[2]."</name><link>".$m[1]."</link>\n";
}
But I'd recommend using DOM for this task instead.
$doc = new DOMDocument;
$doc->loadHTML($html); // load the HTML data
foreach ($doc->getElementsByTagName('a') as $link) {
echo "<name>".$link->nodeValue."</name><link>".$link->getAttribute('href')."</link>\n";
}
eval.in
you can something like this
$xml = '';
$show = 'One
Two
Three';
preg_match_all("/<a href=\"(.+?)\">(.+?)<\/a>/", $show, $display);
for($i=0; $i<count($display[0]); $i++){
$xml .= "<name>".$display[2][$i]."</name><link>".$display[1][$i]."</link>";
}
echo $xml;
and this will output
<name>One</name><link>http://website.com/one</link><name>Two</name><link>http://website.com/two</link><name>Three</name><link>http://website.com/three</link>
DEMO

PHP Get all Urls from string

So I'm trying to get all the urls from a string with a script that looks like this:
$file = file_get_contents('something.txt');
function getUrls($string) {
preg_match_all('~href=("|\')(.*?)\1~', $string, $out);
print_r($out);
}
getUrls($file);
The urls contained in this document may be imperfect - i.e. "/blah/blah.asp?2". The problem is that when I run this script, I get an array that looks something like this:
Array
(
[0] => Array
(
[0] => href="#A"
[1] => href="#B"
[2] => href="#C"
)
[1] => Array
(
[0] => "
[1] => "
[2] => "
)
[2] => Array
(
[0] => #A
[1] => #B
[2] => #C
)
)
Any idea what could be going on here? I have no idea why it is returning alphabetical lists with hash signs instead of the desired urls. How can I go about just returning the urls?
The way of evil:
$file = file_get_contents('something.txt');
function displayUrls($string) {
$pattern = '~\bhref\s*+=\s*+["\']?+\K(?!#)[^\s"\'>]++~';
preg_match_all($pattern, $string, $out);
print_r($out[0]);
}
displayUrls($file);
The good way:
$doc = new DOMDocument();
#$doc->loadHTMLFile('something.txt');
$links = $doc->getElementsByTagName('a');
foreach($links as $link) {
$href = $link->getAttribute('href');
if ($href[0] != '#') $result[] = $href;
}
print_r($result);

Split string between less and greater than

I need to split this kind of strings to separate the email between less and greater than < >. Im trying with the next regex and preg_split, but I does not works.
"email1#domain.com" <email1#domain.com>
News <news#e.domain.com>
Some Stuff <email-noreply#somestuff.com>
The expected result will be:
Array
(
[0] => "email1#domain.com"
[1] => email#email.com
)
Array
(
[0] => News
[1] => news#e.domain.com
)
Array
(
[0] => Some Stuff
[1] => email-noreply#somestuff.com
)
Code that I am using now:
foreach ($emails as $email)
{
$pattern = '/<(.*?)>/';
$result = preg_split($pattern, $email);
print_r($result);
}
You may use some of the flags available for preg_split: PREG_SPLIT_DELIM_CAPTURE and PREG_SPLIT_NO_EMPTY.
$emails = array('"email1#domain.com" <email1#domain.com>', 'News <news#e.domain.com>', 'Some Stuff <email-noreply#somestuff.com>');
foreach ($emails as $email)
{
$pattern = '/<(.*?)>/';
$result = preg_split($pattern, $email, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
print_r($result);
}
This outputs what you expect:
Array
(
[0] => "email1#domain.com"
[1] => email1#domain.com
)
Array
(
[0] => News
[1] => news#e.domain.com
)
Array
(
[0] => Some Stuff
[1] => email-noreply#somestuff.com
)
Splitting on something removes the delimiter (i.e. everything the regex matches). You probably want to split on
\s*<|>
instead. Or you can use preg_match with the regex
^(.*?)\s*<([^>]+)>
and use the first and second capturing groups.
This will do the job. click here for Codepad link
$header = '"email1#domain.com" <email1#domain.com>
News <news#e.domain.com>
Some Stuff <email-noreply#somestuff.com>';
$result = array();
preg_match_all('!(.*?)\s+<\s*(.*?)\s*>!', $header, $result);
$formatted = array();
for ($i=0; $i<count($result[0]); $i++) {
$formatted[] = array(
'name' => $result[1][$i],
'email' => $result[2][$i],
);
}
print_r($formatted);
preg_match_all("/<(.*?)>/", $string, $result_array);
print_r($result_array);
$email='"email1#domain.com" <email1#domain.com>
News <news#e.domain.com>
Some Stuff <email-noreply#somestuff.com>';
$pattern = '![^\>\<]+!';
preg_match_all($pattern, $email,$match);
print_r($match);
Ouput:
Array ( [0] => Array (
[0] => "email1#domain.com"
[1] => email1#domain.com
[2] => News
[3] => news#e.domain.com
[4] => Some Stuff
[5] => email-noreply#somestuff.com ) )
You can also split by <, and get rid of ">" in $result
$pattern = '/</';
$result = preg_split($pattern, $email);
$result = preg_replace("/>/", "", $result);

Categories