php get first and second word after (at) - php

I need some help with a php code which torment me 2-3 hours. Ny methods tried but no result. I want to take the first and second word after the #, eg #John Doe and php result took me John and Doe
I thing something that:
(Edited)
$q = 'Hi #Stefan Simeonov kak si? #Krasi avramov';
if (preg_match_all("(#[^ ]+[ ][^ ]+)", $q, $match)) {
foreach ($match[0] as $singleMatch) {
$finded[] = $singleMatch;
$success = 1;
}
} elseif (preg_match_all("(#[^ ]+)", $q, $match)) {
foreach ($match[0] as $singleMatch) {
$finded[] = $singleMatch;
$success = 1;
}
} else {
$success = 0;
}
if($success = 1) {
$replace = $q;
foreach ($finded as $user) {
$expl = explode("#",$user);
$rep = ''.$expl[1].'';
$replace = str_replace($user,$rep,$replace);
}
echo $replace;
} else {
echo $q;
}

Using a regular expression for example:
<?php
$q = 'Hi #John Doe kak si?';
if (preg_match('/#(\w+)\s(\w+)/', $q, $matches)) {
var_dump($matches);
}
This will look for a word after a #, followed by a space, followed by another word.

You can do something like this:
<?
$q = 'Hi #John Doe kak si?';
$explodeTab = explode("#",$q);
$words = explode(" ",$explodeTab[1]);
print_r($words);
?>
WORKING CODE

You can use a regex of (#[^ ]+[ ][^ ]+) for this:
<?php
$q = 'Hi #Stefan Simeonov kak si?';
if (preg_match_all("(#[^ ]+[ ][^ ]+)", $q, $match)) {
foreach ($match[0] as $singleMatch) {
echo 'Found match: ' . $singleMatch . PHP_EOL;
}
}
?>
Will output:
Found match: #Stefan Simeonov

Assuming that words are always separated by spaces, you can achieve this by first splitting the input string on the # character and then taking the 1th item and splitting that on the space character and reducing that result to the words that you need.
<?php
$q = 'Hi #John Doe kak si?';
$atSplitResult = explode('#', $q);
$spaceSplitResult = explode(' ', $atSplitResult[1]);
$firstTwoWords = array_slice($spaceSplitResult, 0, 2);
var_dump($firstTwoWords);

Let's say, we have a sentence
Let's see, #mike, how are you doing?
now:
$atExploded = explode('#', $str); //where $str is our string
if(count($atExploded)){
foreach($atExploded as $at){
$spaceExplode = explode(' ', $at);
echo $spaceExplode[0].' '.$spaceExplode[1]; //after checking that [0] and [1] are reachable
}
}
of course you should cut any unwanted characters (like braces, colons and so on) but I hope you get the idea.

PHP
$string = 'Hi #John Doe kak si?';
$regex = preg_match("/#(.+?)\s(.+?)\s/", $string, $matches);
var_dump($matches);
Returns
array(3) { [0]=> string(10) "#John Doe " [1]=> string(4) "John" [2]=> string(3) "Doe" }

You can write something like this. This will output #John Doe
<?php
$q = 'Hi #John Doe kak si?';
$q = preg_match('/#[A-Za-z]+\s[A-Za-z]+/', $q, $match);
print_r($match);
?>

Related

Reading information from CSS in PHP

I am creating a website where users shall be able to upload plugins with a file called 'info.css'. I want my PHP-file to be able to read out information from this file, for example the ID.
The 'info.css' file will contain something similar to:
/*
ID: test-preset;
Name: Test Preset;
*/
I want the ID and Name to get into separate strings, without the 'id:' or 'name:'.
Please write any solution you may will work. I have tried with following (but have gotten stuck on the way. Please note that the information in the 'info.css' file may appear in a different order, so for example it should work if the 'Name:' comes first.
$preset_inf = strtolower($preset_inf);
$preset_inf = explode('*/', $preset_inf);
$preset_inf = str_replace('/*', '', $preset_inf[0]);
$preset_inf = str_replace(' ', '', $preset_inf);
$preset_inf = explode(';', $preset_inf);
Regex?
$str = "/*
ID: test-preset;
Name: Test Preset;
*/";
preg_match_all("/(ID|Name):\s*(.*?)\;/s", $str, $m);
var_dump($m);
This will produce:
array(3) {
[0]=>
string(35) "ID: test-preset;
Name: Test Preset;"
[1]=>
string(11) "test-preset"
[2]=>
string(11) "Test Preset"
}
Matches anything between ID/Name and ;.
Edit noticed it could be the other way around too. Edited the code.
The output array will look slightly different but the part you want is in $m[2] array.
https://3v4l.org/iusmV
You can use regex to retrieve each variable, so:
preg_match( '/Name: (.*?);/', $css_file, $match );
$name = $match[1];
echo $name;
preg_match( '/ID: (.*?);/', $css_file, $match );
$id = $match[1];
echo $id;
Would return
Test Preset
test-preset
In case you need a more general solution, here is a regex that will parse a header with an arbitrary number of options along with their names:
$string = '/*
ID: test-preset;
Name: Test Preset;
*/';
$pattern = '/^(?!\/\*)([^:]+):([^:]+);$/mU';
preg_match_all($pattern, $string, $matches, PREG_SET_ORDER, 0);
$results = array();
foreach($matches as $match){
$results[$match[1]] = $match[2];
}
$results now contains an array with this structure:
[
"ID" => "test-preset",
"Name" => "Test Preset"
]
This has the benefit of being able to handle any number of "Header arguments".
Scalable solution.
$presetInfoItem = [];
$presetInfo = [];
$presetFile = "/*
ID: test-preset;
Name: Test Preset;
*/";
$fields = ['ID', 'Name'];
foreach ($fields as $field) {
$matchesCount = preg_match_all("#$field:(?'$field'[\w-\s]*);#", $presetFile, $presetInfoItem);
if ($matchesCount === 0 || $matchesCount === false) {
$presetInfo[$field] = "";
} else {
$presetInfo[$field] = trim($presetInfoItem[$field][0]);
}
}
var_export($presetInfo);
For your pleasure:
<?php
$css = '/*
ID: test-preset;
Name: Test Preset;
*/';
$css = str_replace("*/", "", $css);
$css = str_replace("/*", "", $css);
$css = str_replace(";", "", $css);
$css = trim($css);
$lines = explode("\n", str_replace("\r", '', $css));
if(!empty($lines)) {
foreach($lines as $i => $line) {
$vals = explode(":", $line);
$key = $vals[0];
$value = $vals[1];
echo '<div><b>'.$key.'</b>: '.$value.'</div>';
}
}
?>
Result is:
ID: test-preset
Name: Test Preset
Regex is not needed :)

How to get only characters highlighted from a string in php?

I have a string and some words, i want to highlight those words which match with string, and also i want to print only those words which are highlighted, like if apple matches, then only apple must be printed.
$string = "apple computer";
$keyword = "apple,orange,bike";
I am using the following function to highlight specific characters in a string.
$str = preg_replace("/($keyword)/i","<span style='color:orange;'>$0</span>",$string);
The problem is I want to show only those characters which are highlighted, currently it shows all the characters.
This would meet your need.
$string = " apple computer orange";
$keywords = "apple, orange";
$exp_kwd = explode(",", $keywords);
$res = "<span style='color:orange;'>";
foreach($exp_kwd as $val){
if(strpos($string, trim($val))){
$res .= $val." ";
}
}
$res = $res."</span>";
echo $res;
Hopefully this also will work
$string = "apple computer orange tested";
$keyword = "apple,orange,bike,tested";
$pattern="/".str_replace(",","/,/",$keyword)."/";
$pattern=explode(",",$pattern);
$string=explode(" ",$string);
$keyword =explode(",",$keyword);
$string=implode(",",(preg_filter($pattern, $keyword, $string)));
echo $string="<span style='color:orange;'>$string</span>";
$string = "Im On #Here";
$keyword = "#";
$var = strrchr($string,$keyword);
if(empty($var))
{
echo 'No Occerunce Found';
}
else
{
echo '<span style="color:orange;">'.$var.'</span>';
}
phpfiddle Preview

PHP Regex get reverse number

i have this:
$pattern = 'dev/25{LASTNUMBER}/P/{YYYY}'
$var = 'dev/251/P/2014'
in this situation {LASTNUMBER} = 1 how to get this from $var
vars in pattern can by more always in {}
pattern can by different example :
$pattern = '{LASTNUMBER}/aa/bb/P/{OtherVar}'
in this situation var will by 1/aa/bb/p/some and want get 1
I need get {LASTNUMBER} have pattern and have results
Ok maybe is not possible :) or very very hard
use a regex..
if (preg_match('~dev/25([0-9])/P/[0-9]{4}~', $var, $m)) {
$lastnum = $m[1];
}
$parts = explode("/", $pattern);
if (isset($parts[1])) {
return substr($parts[1], -1);
}
will be faster than regex :)
You probably need this:
<?php
$pattern = 'dev/251/P/2014';
preg_match_all('%dev/25(.*?)/P/[\d]{4}%sim', $pattern, $match, PREG_PATTERN_ORDER);
$match = $match[1][0];
echo $match; // echo's 1
?>
Check it online
If you need to loop trough results you can use:
<?php
$pattern = <<< EOF
dev/251/P/2014
dev/252/P/2014
dev/253/P/2014
dev/254/P/2014
dev/255/P/2014
EOF;
preg_match_all('%dev/25(.*?)/P/[\d]{4}%sim', $pattern , $match, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($match[1]); $i++) {
echo $match[1][$i]; //echo's 12345
}
?>
Check in online

Use a regex match as an array pointer

I want to replace some numbers in a string with the content of the array in the position which this number points to.
For example, replace "Hello 1 you are great", with "Hello myarray[1] you are great"
I was doing the next: preg_replace('/(\d+)/','VALUE: ' . $array[$1],$string);
But it does not work. How could I do it?
You should use a callback.
<?php
$str = 'Hello, 1!';
$replacements = array(
1 => 'world'
);
$str = preg_replace_callback('/(\d+)/', function($matches) use($replacements) {
if (array_key_exists($matches[0], $replacements)) {
return $replacements[$matches[0]];
} else {
return $matches[0];
}
}, $str);
var_dump($str); // 'Hello, world!'
Since you are using a callback, in the event that you actually want to use a number, you might want to encode your strings as {1} or something instead of 1. You can use a modified match pattern:
<?php
// added braces to match
$str = 'Hello, {1}!';
$replacements = array(
1 => 'world'
);
// added braces to regex
$str = preg_replace_callback('/\{(\d+)\}/', function($matches) use($replacements) {
if (array_key_exists($matches[1], $replacements)) {
return $replacements[$matches[1]];
} else {
// leave string as-is, with braces
return $matches[0];
}
}, $str);
var_dump($str); // 'Hello, world!'
However, if you are always matching known strings, you may want to use #ChrisCooney's solution because it offers less opportunity to screw up the logic.
The other answer is perfectly fine. I managed it this way:
$val = "Chris is 0";
// Initialise with index.
$adj = array("Fun", "Awesome", "Stupid");
// Create array of replacements.
$pattern = '!\d+!';
// Create regular expression.
preg_match($pattern, $val, $matches);
// Get matches with the regular expression.
echo preg_replace($pattern, $adj[$matches[0]], $val);
// Replace number with first match found.
Just offering another solution to the problem :)
$string = "Hello 1 you are great";
$replacements = array(1 => 'I think');
preg_match('/\s(\d)\s/', $string, $matches);
foreach($matches as $key => $match) {
// skip full pattern match
if(!$key) {
continue;
}
$string = str_replace($match, $replacements[$match], $string);
}
<?php
$array = array( 2 => '**', 3 => '***');
$string = 'lets test for number 2 and see 3 the result';
echo preg_replace_callback('/(\d+)/', 'replaceNumber', $string);
function replaceNumber($matches){
global $array;
return $array[$matches[0]];
}
?>
output
lets test for number ** and see *** the result

PHP: How to find text NOT between particular tags?

Example input string: "[A][B][C]test1[/B][/C][/A] [A][B]test2[/B][/A] test3"
I need to find out what parts of text are NOT between the A, B and C tags. So, for example, in the above string it's 'test2' and 'test3'. 'test2' doesn't have the C tag and 'test3' doesn't have any tag at all.
If can also be nested like this:
Example input string2: "[A][B][C]test1[/B][/C][/A] [A][B]test2[C]test4[/C][/B][/A] test3"
In this example "test4" was added but "test4" has the A,B and C tag so the output wouldn't change.
Anyone got an idea how I could parse this?
This solution is not clean but it does the trick
$string = "[A][B][C]test1[/B][/C][/A] [A][B]test2[/B][/A] test3" ;
$string = preg_replace('/<A[^>]*>([\s\S]*?)<\/A[^>]*>/', '', strtr($string, array("["=>"<","]"=>">")));
$string = trim($string);
var_dump($string);
Output
string 'test3' (length=5)
Considering the fact that everyone of you tags is in [A][/A] What you can do is: Explode the [/A] and verify if each array contains the [A] tag like so:
$string = "[A][B][C]test1[/B][/C][/A] [A][B]test2[/B][/A] test3";
$found = ''; // this will be equal to test3
$boom = explode('[/A]', $string);
foreach ($boom as $val) {
if (strpos($val, '[A] ') !== false) { $found = $val; break; }
}
echo $found; // test3
try the below code
$str = 'test0[A]test1[B][C]test2[/B][/C][/A] [A][B]test3[/B][/A] test4';
$matches = array();
// Find and remove the unneeded strings
$pattern = '/(\[A\]|\[B\]|\[C\])[^\[]*(\[A\]|\[B\]|\[C\])[^\[]*(\[A\]|\[B\]|\[C\])([^\[]*)(\[\/A\]|\[\/B\]|\[\/C\])[^\[]*(\[\/A\]|\[\/B\]|\[\/C\])[^\[]*(\[\/A\]|\[\/B\]|\[\/C\])/';
preg_match_all( $pattern, $str, $matches );
$stripped_str = $str;
foreach ($matches[0] as $key=>$matched_pattern) {
$matched_pattern_str = str_replace($matches[4][$key], '', $matched_pattern); // matched pattern with text between A,B,C tags removed
$stripped_str = str_replace($matched_pattern, $matched_pattern_str, $stripped_str); // replace pattern string in text with stripped pattern string
}
// Get required strings
$pattern = '/(\[A\]|\[B\]|\[C\]|\[\/A\]|\[\/B\]|\[\/C\])([^\[]+)(\[A\]|\[B\]|\[C\]|\[\/A\]|\[\/B\]|\[\/C\])/';
preg_match_all( $pattern, $stripped_str, $matches );
$required_strings = array();
foreach ($matches[2] as $match) {
if (trim($match) != '') {
$required_strings[] = $match;
}
}
// Special case, possible string on start and end
$pattern = '/^([^\[]*)(\[A\]|\[B\]|\[C\]).*(\[\/A\]|\[\/B\]|\[\/C\])([^\[]*)$/';
preg_match( $pattern, $stripped_str, $matches );
if (trim($matches[1]) != '') {
$required_strings[] = $matches[1];
}
if (trim($matches[4]) != '') {
$required_strings[] = $matches[4];
}
print_r($required_strings);

Categories