basic string separation in php - php

I have an alphanumeric string like 1234and5678.
I want to store the numbers preceding and i.e 1234 into one variable and the number after and i.e 5678 into another variable as shown below:
$var1=1234;
$var2=5678;
also what should do if i replace and by some random special characters like #$% etc.
Can you please help me out?
Thanks in advance.

$string = "1234and5678";
list($before, $after) = explode("and", $string);
This splits the string into two variables based on the delimeter ("and"), whatever is before and is saved in a variable called $before, whatever is after is saved into a variable called $after

Use split http://php.net/manual/en/function.split.php with "and" as separator. That should give you an array with the two numbers.

you can use preg_split() function, in your case: $var = preg_split("/[\D]+/", "1234and5678"); That gives you $var[0] = '1234' and $var[1] = '5678'
According to you edit, you can:
replace regex on any another that you need (e.g. $var = preg_split("/[\d]+/", "1234and5678"); for any non-numeric element)
use preg_match_all("/(\d+)/","1234and5678", $var) to find any numbers in your string

Use regular expressions. I provided a link for regexes in php. Split is deprecated as of version 5.3.0 and you should not rely on it.
Perl compatible regular expressions

Related

Regex issue: replace the first and the last $ character from all the elements of an array

I am trying to replace few words from a huge string with preg_replace()
using it like this :
preg_replace($match[0], $variable_value_array, $form_body)
Here $match[0] is an array with value in it in the form like:
$contacts-firstname$
$contacts-lastname$
$contacts-mobile$
$leads-leadstatus$
$leads-noofemployees$
and $variable_value_array is also an array with values in it like :
Linda
William
(091) 115-9385
Value Not Present
Value Not Present
and $form_body is a really long string.
The function is replacing the values of $form_body but instead of replacing the whole $contacts-firstname$ with Linda it is replacing only contacts-firstname with Linda making it like $Linda$. What should i do to replace both the $ sigh's as well ?
Thanks.
That's because $ is interpreted as the delimiter of your regex. You should use a simple str_replace instead. The signature is exactly the same:
str_replace($match[0], $variable_value_array, $form_body);
If you desperately wanted to use preg_replace you need to do two things. Firstly, you need to wrap every array element in explicit delimiters (/ is kind of the standard choice). And also you need to run every array element through preg_quote, otherwise the $ will be treated as an end-of-string anchors:
$patterns = array();
foreach($match[0] as $value)
$patterns[] = '/'.preg_quote($value, '/').'/';
And then use $patterns instead of $match[0]. But that is only intended as a nice-to-know if you ever actually need to use an array of literal search-strings inside a more complex pattern.
Try str_replace instead of preg_replace its faster and much appropriate for your use case

preg_split url with a regular expression

I have an string e.g.:
src="http://www.domain.com/sub_folder/xyz_17215_andso_on_01-file_08.html"
and want to split this at every character that is not a letter or number.
With
/[a-z0-9]/
I get an array with all the characters but what's the opposite of it to get all the words and numbers?
You can write:
$result_array = preg_split('/[^a-z0-9]+/', $string_to_split);
Rather than writing new code to solve a problem, use the built-in functionality that PHP provides to you in the parse_url() function: http://php.net/manual/en/function.parse-url.php

How to match a regular expression that contains an arbitrary string, and get only that arbitrary string into a variable using PHP?

I'm trying to write a very simple markup language in PHP that contains tags like [x=123], and I need to be able to match that tag and extract only the value of x.
I'm assuming the answer involves regex but maybe I'm wrong.
So if we had a string:
$str = "F9F[x=]]^$^$[x=123]#3j3E]]#J";
And a regular expression to match:
/^\[x=.+\]$/
How would we get only the ".+" portion of the matching string into a variable?
You can use preg_match to search a string for a regular expression.
Check out the documentation here: http://www.php.net/manual/en/function.preg-match.php for more information on how to use it (as well as some examples). You might also want to take a look at preg_grep.
Following code should work for you:
$str = "F9F[x=]]^$^$[x=123]#3j3E]]#J";
if (preg_match('~\[x=(?<valX>\d+)\]~', $str, $match))
echo $match['valX'] . "\n";
OUTPUT:
123

Replace array values in string with regex?

Say I have the following array and string:
$array = array('$AA', '$AB', '$AC', '$ZZ');
$string = 'String mentioning $AA and $AB and $CZ and $MARTASS';
I want to check $string for matches against $array. Every word in $string that begins with "$" should be checked. In the example, a match is found for $AA and $AB; not for $CZ. The desired output would be:
String mentioning {MATCH} and {MATCH} and {NO-MATCH}
Is this possible with one regex or is it better to write several lines of PHP? Any input is kindly received :)
Should be possible with two find-and-replaces, done in this order:
first:
\b(($AA)|($AB)|($AC)|($ZZ))\b ---> {MATCH}
second:
\b$\w+\b ---> {NO-MATCH}
I'm not sure this is in PHP syntax, but it shouldn't be too hard to get there. \b is a word separator boundary, which I believe is allowed in PHP.
Edit: You might need to escape $, not sure as it's grouped.
Yes it is possible. Have a look at the examples in the preg_replace_callback() documentation. You would use a replace call of the form:
function substituteVar($matches) {
...
}
...
$newString = preg_replace_callback("/\\$(\w+)/", 'substituteVar', $string);
I think I'll leave the content of the substituteVar() as an "exercise for the reader". :-)
This should work...
<?php
$string = 'String mentioning $AA and $AB and $CZ and $MARTASS';
echo preg_replace_callback("/\\$\S+/",
create_function('$a','return in_array($a[0],array("\$AA", "\$AB", "\$AC", "\$ZZ")) ? "{MATCH}" : "{NO-MATCH}";'),
$string
);
?>
Regex matches $ followed by one or more not spaces (\S+) and then checks if the matched string is in the array (included in create function definition so it is in scope, and escaped properly)
I wouldn't bother using a regex here, a simple scan of the string from start to finish, looking for the '$' character and then performing a binary search on the array would be much simpler and faster.

regular expr question

i'v got such string <>1 <>2 <>3
i want remove all '<>' and symbols after '<>' i want replace with such expression like www.test.com/1.jpg, www.test.com/2.jpg, www.test.com/3.jpg
is it possible to do with regex? i only know to find '/<>.?/'
preg_replace('/<>(\d+)/g', 'www.test.com/bla/$1.jpg', $input);
(assuming your replaced elements are just numbers. If they are more general, you'll need to replace '\d+' by something else).
str_replace('<>', 'www.test.com/', $input);
// pseudo code
pre_replace_all('~<>([0-9]+)~', 'www.test.com/$1.jpg', $input);
$string = '<>1 <>2 <>3';
$temp = explode(' ',preg_replace('/<>(\d)/','www.test.com/\1.jpg',$string));
$newString = implode(', ',$temp);
echo $newString;
Based on your example, I don’t think you need regex at all.
$str = '<>1 <>2 <>3';
print_r(str_replace('<>', 'www.test.com/', $str));
Regex's allow you to manipulate a string in any fashion you desire, to modify the string in the fashion you desire you would use the following regex:
<>(\d)
and you would use regex back referencing to keep the values you have captured in your grouping brackets, in this case a single digit. The back reference is typically signified by the $ symbol and then the number of the group you are referencing. As follows:
www.test.com/$1
this would be used in a regex replace scenario which would be implemented in different ways depending on the language you are implementing your regex replace method in.

Categories