reqular exp to get last number from string - php

Hi all
how can i get number(positive num) from string,if string syntax is the following:
t_def_type_id_2 t_def_type_id_22 t_def_type_id_334
so,in the first string i want to get 1,and in the second i want to get 22 and in the third string i want to get 334 using preg_match_all or any other sutable php function

You can use the regex
\d+$
with preg_match

if there is only one number in the string, simply use \d+

Try this:
preg_match('/^\w+(\d+)$/U', $string, $match);
$value = (int) $match[1];

You can use
str_replace('t_def_type_id_','');

what about following code:
^[\d]+(\d+)$

You can use preg_replace():
$defTypeID = preg_replace("/^(.*?)(\d+)$/", "$2", $defTypeIDString);

$string = "t_def_type_id_2
t_def_type_id_22
t_def_type_id_334";
preg_match_all("#t_def_type_id_([0-9]+)#is", $string, $matches);
$matches = $matches[1];
print_r($matches);
Result:
Array
(
[0] => 2
[1] => 22
[2] => 334
)

If it's always the last thing in your string, then using a banal string function approach is possible and looks a bit compacter:
$num = ltrim(strrchr($string, "_"), "_");

You may use
^\w+(\d+)$
but I did not test

Here's my alternative solution.
$number = array_pop(explode('_', $string));

Related

How to pick numbers between underlines using regex?

I want to get only the value in bold, but I'm not getting.
349141_194419414_4828414_n.jpg
or
https:// hphotos-ash3.net/t1.0-9/1146_54482593153_1214114_n.jpg
Thank you already
You can use preg_match with a capture group to get the result:
<?php
$searchText = "349141_194419414_4828414_n.jpg";
$result = preg_match("/_(\\d+)_/u", $searchText, $matches);
print_r($matches[1]);
?>
output:
194419414
(i'm not sure whether this one is good method or not but you can get whatever value you want to by this)
$r="349141_194419414_4828414_n";
print_r(explode('_',$r));
output:
Array ( [0] => 349141 [1] => 194419414 [2] => 4828414 [3] => n )
$rr=explode('_',$r);
echo $rr[1];
output
194419414
Try something like this:
.+/\d+_(\d+)_\d+_n.jpg
Here's a regular expression answer.
$filename = '349141_194419414_4828414_n.jpg';
preg_match_all('/[0-9]+/', $filename, $matches);
echo $matches[0][1]; //194419414

Pattern for splitting a string

I'm looking to split this string:
/server hostname:port username:password
into:
Array ( [0] => hostname
[1] => port
[2] => username:password )
I don't wish for /server to be stored.
Hostname, port, username and password will all vary in lengths.
I'm not sure if I should be using preg_split for this, and what the matching pattern should be?
Thanks
Exploding the string and splitting it's parts can get you what you need. Note that the example below does nothing to check the string is actually in that format. It would be wise to check that.
$str = '/server hostname:port username:password';
$bits = explode(" ",$str,3);
list($hostname,$port) = explode(':',$bits[1]);
list($username,$password) = explode(':',$bits[2]);
Edit to create what you need:
$str = '/server hostname:port username:password';
$bits = explode(" ",$str,3);
list($hostname,$port) = explode(':',$bits[1]);
$arr = array($hostname,$port,$bits[2]);
I wouldn't use regex for this, instead, try this
$str="/server hostname:port username:password";
$arr=explode(" ",$str);
$newarr=array(explode(":",$arr[1])[0],explode(":",$arr[1])[1],$arr[2]);
Here is a test for it
See explode function, it will do the job
Depending on the input format parse_url() could be an option.
$str = '/server hostname:port username:pa sword';
if(preg_match("|/server (.+):(.+) ([^:]+:.+)|", $str, $m)){
print_r($m);
}
I recommend preg_match(). For best performance, use negated character classes or limited character ranges to allow the regex engine to perform greedy/possessive matching.
Code: (Demo)
$string = '/server localhost:3306 root:some pass with spaces & a : colon';
preg_match('~/server ([^:]+):(\d+) (.+)~', $string, $m);
array_shift($m); // remove the fullstring match
var_export($m);
Output:
array (
0 => 'localhost',
1 => '3306',
2 => 'root:some pass with spaces & a : colon',
)

php regex how to remove duplicate charactors and make every charactor unique in string

How should one use preg_replace() to replace a string from 'aabbaacc' to 'abc'?
Currently, my code uses str_split() then array_unique() then implode().
I think preg_replace() can achieve this also, but I don't know how.
Thank you for your help.
A regex that seems to work for me is /(.)(?=.*?\1)/. Please test it for yourself here:
http://regexpal.com/
I've also tested it with preg_replace('/(.)(?=.*?\1)/', '', 'aaabbbabc') which returns the expected abc.
Hope this helps :)
This is the closest I got. However, it's basically a copy of :
How do I remove duplicate characters and keep the unique one only in Perl?
<?php
$string = 'aabbaacc';
$new = preg_replace( '/(.)(?=.*?\1)/i','', $string );
echo $new;
?>
Unfortunately, it does not keep the string in the same order. I don't know if that is important to you or not.
try this
$string = 'dbbaabbbaac';
$new = preg_replace_callback( array("/(.)\\1+/"),function($M){print_r($M);return $M[1];}, $string );
$new = preg_replace_callback( array('/(.)(.?\\1)/i','/(.)(.*?\\1)/i'),function($M){return $M[1].trim($M[2],$M[1]);}, $new );
echo $new."\n";
output
dbac
or this with out Regex
$value="aabbaacc";
for($i=0;$i<strlen($value);$i++){
$out[$value[$i]]=$value[$i];
}
echo implode("",$out);
output:
abc

PHP -- need to explode a string with 2 different delimiters

I've got a string $newstring loaded with lines that look like:
<tt>Thu 01-Mar-2012</tt> 7th of Atrex, 3009 <br>
I want to explode $newstring using <tt> and <br> as the delimiters.
How can I use preg_split() or anything else to explode it?
Alright I'm on my Nexus 7, and I've found it isn't too elegant to answer questions on a tablet, but regardless you can do this using preg_split using the following regex:
<\/?tt>|</?br>
See the regex working here: http://www.regex101.com/r/kX0gE7
PHP code:
$str = '<tt>Thu 01-Mar-2012</tt>  7th of Atrex, 3009<br>';
$split = preg_split('#<\/?tt>|</?br>#', $str);
var_export($split);
The array $split will contain:
array (
0 => '',
1 => 'Thu 01-Mar-2012',
2 => ' 7th of Atrex, 3009',
3 => ''
)
(See http://ideone.com/aiTi5U)
You should try this code..
<?php
$keywords = preg_split("/\<tt\>|\<br\>/", "<tt>Thu 01-Mar-2012</tt> 7th of Atrex, 3009 <br>");
print_r($keywords);
?>
Look at the CodePad exapmle.
IF you want to include </tt> also then use.. <\/?tt>|<br>. See Example.
try this code..
<?php
$newstring = "<tt>Thu 01-Mar-2012</tt> 7th of Atrex, 3009<br>";
$newstring = (explode("<tt>",$newstring));
//$newstring[1] store Thu 01-Mar-2012</tt> 7th of Atrex, 3009<br> so do opration on that.
$newstring = (explode("<br>",$newstring[1]));
echo $newstring[0];
?>
output:-->
Thu 01-Mar-2012</tt> 7th of Atrex, 3009
If the <tt> and <br/> tags are the only tags in the string, a simple regex like this will do:
$exploded = preg_split('/\<[^>]+\>/',$newstring, PREG_SPLIT_NO_EMPTY);
The expression:
delimiters start and end with < and > respectively
In between these chars at least 1 [^>] is expected (this is any char except for the closing >
PREG_SPLIT_NO_EMPTY
This is a constant, passed to the preg_split function that avoids array values that are empty strings:
$newString = '<tt>Foo<br/><br/>Bar</tt>';
$exploded = preg_split('/\<[^>]+\>/',$newstring);
//output: array('','Foo','','Bar',''); or something (off the top of my head)
$exploded = preg_split('/\<[^>]+\>/',$newstring, PREG_SPLIT_NO_EMPTY);
//output: array('Foo', 'Bar')
If, however, you're dealing with more than these two tags, or variable input (as in user-supplied), you might be better off parsing the markup. Look into php's DOMDocument class, see the docs here.
PS: to see the actual output, try echo '<pre>'; var_dump($exploded); echo '</pre>';
function multiExplode($delimiters,$string) {
return explode($delimiters[0],strtr($string,array_combine(array_slice($delimiters,1),array_fill(0,count($delimiters)-1,array_shift($delimiters)))));
}
EX: $values = multiExplode(array("",""),$your_string);
Here is a custom function with example.
http://www.phpdevtips.com/2011/07/exploding-a-string-using-multiple-delimiters-using-php/

regex split string at first line break

I would like to split a string at the first line break, instead of the first blank line
'/^(.*?)\r?\n\r?\n(.*)/s' (first blank line)
So for instance, if I have:
$str = '2099 test\nAre you sure you
want to continue\n some other string
here...';
match[1] = '2099 test'
match[2] = 'Are you sure you want to continue\n some other string here...'
preg_split() has a limit parameter you can take to your advantage. You could just simply do:
$lines = preg_split('/\r\n|\r|\n/', $str, 2);
<?php
$str = "2099 test\nAre you sure you want to continue\n some other string here...";
$match = explode("\n",$str, 2);
print_r($match);
?>
returns
Array
(
[0] => 2099 test
[1] => Are you sure you want to continue
some other string here...
)
explode's last parameter is the number of elements you want to split the string into.
Normally just remove on \r?\n:
'/^(.*?)\r?\n(.*)/s'
You can use preg_split as:
$arr = preg_split("/\r?\n/",$str,2);
See it on Ideone
First line break:
$match = preg_split('/\R/', $str, 2);
First blank line:
$match = preg_split('/\R\R/', $str, 2);
Handles all the various ways of doing line breaks.
Also there was a question about splitting on the 2nd line break. Here is my implementation (maybe not most efficient... also note it replaces some line breaks with PHP_EOL)
function split_at_nth_line_break($str, $n = 1) {
$match = preg_split('/\R/', $str, $n+1);
if (count($match) === $n+1) {
$rest = array_pop($match);
}
$match = array(implode(PHP_EOL, $match));
if (isset($rest)) {
$match[] = $rest;
}
return $match;
}
$match = split_at_nth_line_break($str, 2);
Maybe you don't even need to use regex's. To get just split lines, see:
What's the simplest way to return the first line of a multi-line string in Perl?

Categories