Getting a word after a specific character in PHP - php

I want to get the words in a string where a specific character stands before, in this case, its the : character.
textexjkladjladf :theword texttextext :otherword :anotherword
From this snippet the expected output will be:
theword
otherword
anotherword
How do i do this with PHP?

You can use regular expression:
$string = "textexjkladjladf :theword texttextext :otherword :anotherword";
$matches = array();
preg_match_all('/(?<=:)\w+/', $string, $matches);
foreach ($matches[0] as $item) {
echo $item."<br />";
}
Output is:
theword
otherword
anotherword
The array what you want is the $matches[0]

Another way of getting those words without Regular Expression can be:
Use explode(' ',$str) to get all the words.
Then loop the words and check which one starts with ':'.

try
$str = 'textexjkladjladf :theword texttextext :otherword :anotherword';
$tab = exlode(':',$str);
print_r($tab);
//if echo entry 0 =>
echo $tab[0]; // => textexjkladjladf

Related

Replacing values in string

I have a string which contains certain number of #{number} structures. For example:
#328_#918_#1358
SKU:#666:#456
TEST--#888/#982
For each #{number} structure, I have to replace it with a known string.
For the first example:
#328_#918_#1358
I have the following strings:
328="foo"
918="bar"
1358"arg"
And the result should be:
foo_bar_arg
How do I achieve such effect? My current code looks like that:
$matches = array();
$replacements = array();
// starting string
$string = "#328_#918:#1358";
// getting all the numbers from the string
preg_match_all("/\#[0-9]+/", $string, $matches);
// getting rid of #
foreach ($matches[0] as $key => &$feature) {
$feature = preg_replace("/#/", "", $feature);
} // end foreach
// obtaining the replacement values
foreach ($matches[0] as $key => $value) {
$replacement[$value] = "fizz"; // here the value required for replacement is obtained
} // end foreach
But I have no idea how to actually perform a replacement in $string variable using values from $replacement table. Any help is much appreciated!
You can use a preg_replace_callback solution:
$string = '#328_#918:#1358
SKU:#666:#456
TEST--#888/#982';
$replacements = [328=>"foo", 918=>"bar", 1358=>"arg"];
echo preg_replace_callback("/#([0-9]+)/", function ($m) use ($replacements) {
return isset($replacements[$m[1]]) ? $replacements[$m[1]] : $m[0];
}
,$string);
See the PHP demo.
The #([0-9]+) regex will match all non-overlapping occurrences of # and one or more digits right after capturing them into Group 1. If there is an item in the replacements associative array with the numeric key, the whole match is replaced with the corresponding value. Else, the match is returned so that no replacement could occur and the match does not get removed.

Extract specific data from string using Regex (PHP)

My objective is to check if the message have emojis or not , if yes i am going to convert them.
I am having a problem to find out how many emojis are in the string.
Example :
$string = ":+1::+1::+1:"; //can be any string that has :something: between ::
the objective here is to get the :+1: ( all of them ) but i tried two pattern and i keep getting only 1 match.
preg_match_all('/:(.*?):/', $string, $emojis, PREG_SET_ORDER); // $emojis is declared as $emojis='' at the beginning.
preg_match_all('/:(\S+):/', $string, $emojis, PREG_SET_ORDER);
The Rest of the codeafter getting the matches i am doing this :
if (isset($emojis[0]))
{
$stringMap = file_get_contents("/api/common/emoji-map.json");
$jsonMap = json_decode($stringMap, true);
foreach ($emojis as $key => $value) {
$emojiColon = $value[0];
$emoji = key_exists($emojiColon, $jsonMap) ? $jsonMap[$emojiColon] : '';
$newBody = str_replace($emojiColon, $emoji, $newBody);
}
}
i would appreciate any help or suggestions , Thanks.
I updated your expression a little bit:
preg_match_all('/\:(.+?)(\:)/', $string, $emojis, PREG_SET_ORDER);
echo var_dump($emojis);
The : is now escaped, otherwise it could be treated as special character.
Replaced the * by +, this way you won't match two consecutive :: but require at least one charcter in-between.

PHP Regex for a specific numeric value inside a comma-delimited integer number string

I am trying to get the integer on the left and right for an input from the $str variable using REGEX. But I keep getting the commas back along with the integer. I only want integers not the commas. I have also tried replacing the wildcard . with \d but still no resolution.
$str = "1,2,3,4,5,6";
function pagination()
{
global $str;
// Using number 4 as an input from the string
preg_match('/(.{2})(4)(.{2})/', $str, $matches);
echo $matches[0]."\n".$matches[1]."\n".$matches[1]."\n".$matches[1]."\n";
}
pagination();
How about using a CSV parser?
$str = "1,2,3,4,5,6";
$line = str_getcsv($str);
$target = 4;
foreach($line as $key => $value) {
if($value == $target) {
echo $line[($key-1)] . '<--low high-->' . $line[($key+1)];
}
}
Output:
3<--low high-->5
or a regex could be
$str = "1,2,3,4,5,6";
preg_match('/(\d+),4,(\d+)/', $str, $matches);
echo $matches[1]."<--low high->".$matches[2];
Output:
3<--low high->5
The only flaw with these approaches is if the number is the start or end of range. Would that ever be the case?
I believe you're looking for Regex Non Capture Group
Here's what I did:
$regStr = "1,2,3,4,5,6";
$regex = "/(\d)(?:,)(4)(?:,)(\d)/";
preg_match($regex, $regStr, $results);
print_r($results);
Gives me the results:
Array ( [0] => 3,4,5 [1] => 3 [2] => 4 [3] => 5 )
Hope this helps!
Given your function name I am going to assume you need this for pagination.
The following solution might be easier:
$str = "1,2,3,4,5,6,7,8,9,10";
$str_parts = explode(',', $str);
// reset and end return the first and last element of an array respectively
$start = reset($str_parts);
$end = end($str_parts);
This prevents your regex from having to deal with your numbers getting into the double digits.

How to find the position of multiple words in a string using strpos() function?

I want to find the position of multiple words in a string.
Forexample :
$str="Learning php is fun!";
I want to get the posion of php and fun .
And my expected output would be :-
1) The word Php was found on 9th position
2) The word fun was found on 16th position.
Here is the code that I tried, but it doesn't work for multiple words.
<?Php
$arr_words=array("fun","php");
$str="Learning php is fun!";
$x=strpos($str,$arr_words);
echo The word $words[1] was found on $x[1] position";
echo The word $words[2] was found on $x[2] position";
Does someone know what's wrong with it and how to fix it?
Any help is greatly appriciated.
Thanks!
To supplement the other answers, you can also use regular expressions:
$str="Learning php is fun!";
if (preg_match_all('/php|fun/', $str, $matches, PREG_OFFSET_CAPTURE)) {
foreach ($matches[0] as $match) {
echo "The word {$match[0]} found on {$match[1]} position\n";
}
}
See also: preg_match_all
Since you can't load an array of string words inside strpos, you could just invoke strpos twice, one for fun and one for php:
$arr_words = array("fun","php");
$str = "Learning php is fun!";
$x[1] = strpos($str,$arr_words[0]);
$x[2] = strpos($str,$arr_words[1]);
echo "The word $arr_words[0] was found on $x[1] position <br/>";
echo "The word $arr_words[1] was found on $x[2] position";
Sample Output
Or loop the word array:
$arr_words = array("fun","php");
$str = "Learning php is fun!";
foreach ($arr_words as $word) {
if(($pos = strpos($str, $word)) !== false) {
echo "The word {$word} was found on {$pos} position <br/>";
}
}
Sample Output
$str="Learning php is fun!";
$data[]= explode(" ",$str);
print_r($data);//that will show you index
foreach($data as $key => $value){
if($value==="fun") echo $key;
if($value==="php") echo $key;
}
Key is the exact position but index start with 0 so keep in mind to modify your code accordingly, may be echo $key+1 (a number of ways, depends on you).
You were doing it in a wrong way check the function
strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
haystack
The string to search in.
needle
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
offset
If specified, search will start this number of characters counted from the beginning of the string.
Refer Docs
Here within your example
$arr_words=array("fun","php");
$str="Learning php is fun!";
$x=strpos($str,$arr_words);
$arr_words is an array not a string or not an integer
so you need to loop it or need to manually pass the key as
$x[1] = strpos($str,$arr_words[0]);
$x[2] = strpos($str,$arr_words[1]);
or
foreach($arr_words as $key => $value){
$position = strpos($str,$value);
echo "The word {$value} was found on {$position}th position"
}
Just another answer:
<?php
$arr_words=array("fun","php");
$str="Learning php is fun!";
foreach($arr_words as $needle) {
$x = strpos($str, $needle);
if($x)
echo "The word '$needle' was found on {$x}th position.<br />";
}
?>
You can not use function strpos if the second params is an array.
This is easiest way:
<?php
$words = array("php","fun");
$str = "Learning php is fun!";
foreach ($words as $word) {
$pos = strpos($str, $word);
// Found this word in that string
if($pos) {
// Show you message here
}
}

A bit lost with preg_match regular expression

I'm a beginner in regular expression so it didn't take long for me to get totally lost :]
What I need to do:
I've got a string of values 'a:b,a2:b2,a3:b3,a4:b4' where I need to search for a specific pair of values (ie: a2:b2) by the second value of the pair given (b2) and get the first value of the pair as an output (a2).
All characters are allowed (except ',' which seperates each pair of values) and any of the second values (b,b2,b3,b4) is unique (cant be present more than once in the string)
Let me show a better example as the previous may not be clear:
This is a string: 2 minutes:2,5 minutes:5,10 minutes:10,15 minutes:15,never:0
Searched pattern is: 5
I thought, the best way was to use function called preg_match with subpattern feature.
So I tried the following:
$str = '2 minutes:2,5 minutes:5,10 minutes:10,15 minutes:15,20 minutes:20,30 minutes:30, never:0';
$re = '/(?P<name>\w+):5$/';
preg_match($re, $str, $matches);
echo $matches['name'];
Wanted output was '5 minutes' but it didn't work.
I would also like to stick with Perl-Compatible reg. expressions as the code above is included in a PHP script.
Can anyone help me out? I'm getting a little bit desperate now, as Ive spent on this most of the day by now ...
Thanks to all of you guys.
$str = '2 minutes:2,51 seconds:51,5 minutes:5,10 minutes:10,15 minutes:51,never:0';
$search = 5;
preg_match("~([^,\:]+?)\:".preg_quote($search)."(?:,|$)~", $str, $m);
echo '<pre>'; print_r($m); echo '</pre>';
Output:
Array
(
[0] => 5 minutes:5
[1] => 5 minutes
)
$re = '/(?:^|,)(?P<name>[^:]*):5(?:,|$)/';
Besides the problem of your expression having to match $ after 5, which would only work if 5 were the last element, you also want to make sure that after 5 either nothing comes or another pair comes; that before the first element of the pair comes either another element or the beginning of the string, and you want to match more than \w in the first element of the pair.
A preg_match call will be shorter for certain, but I think I wouldn't bother with regular expressions, and instead just use string and array manipulations.
$pairstring = '2 minutes:2,5 minutes:5,10 minutes:10,15 minutes:15,20 minutes:20,30 minutes:30, never:0';
function match_pair($searchval, $pairstring) {
$pairs = explode(",", $str);
foreach ($pairs as $pair) {
$each = explode(":", $pair);
if ($each[1] == $searchval) {
echo $each[0];
}
}
}
// Call as:
match_pair(5, $pairstring);
Almost the same as #Michael's. It doesn't search for an element but constructs an array of the string. You say that values are unique so they are used as keys in my array:
$str = '2 minutes:2,5 minutes:5,10 minutes:10,15 minutes:15,20 minutes:20,30 minutes:30, never:0';
$a = array();
foreach(explode(',', $str) as $elem){
list($key, $val) = explode(':', $elem);
$a[$val] = $key;
}
Then accessing an element is very simple:
echo $a[5];

Categories