So let's say we have a text like "CS x1CD x2CE x3"
What I want to do is replace each x1 with x1\n, x2 with x2\n, x3 with x3\n, etc. During runtime it is not known before hand what those values will be, but basically after each x[0-9]+ we want to append a newline.
How would I do this? I tried using regex such as
preg_replace("/x[0-9]+/", "${1}\n", $request['item_name']);
But that doesn't work as it just uses the first result.
You can avoid to refer to a capturing group with \K:
$result = preg_replace("/x[0-9]+\K/", "\n", $request['item_name']);
\K removes all on the left from match result.
If your server is running on a linux/unix system, you can skip a good part of the curly/double/single quotes/newline problem using PHP_EOL:
$result = preg_replace("/x[0-9]+/", '$0' . PHP_EOL, $request['item_name']);
You are looking for the following instead.
preg_replace('/x[0-9]+/', '${0}' . "\n", $request['item_name']);
See live demo.
Working Live Demo
Try this:
preg_replace("/(x[0-9]+)/","${0}\n",$request['item_name']);
Try this:
<?php
$string = $request['item_name'];
$string = preg_replace('/(x\d+)/', '$1\n', $string);
echo $string;
?>
DEMO
http://ideone.com/quh4M1
Related
i want to make regex to detect this format image(numeric, string). ex: image(100, 'test').
i have tried this one, but just detect the image(numeric)
/image\((\d+)\)/
Any help with second parameter and the ,?
Also how i can get the second parameter?
You can try the following pattern:
/image\(\d+,\s*'.+?'\)/
I removed the capture group since it would be not needed if using the regex for validation only.
Demo
If you want to capture the number and text, then use capture groups:
$input = "code image(123, 'meh') more code";
if (preg_match("/image\((\d+),\s*'(.+?)'\)/", $input, $m)) {
echo "match";
}
$number = $m[1];
$text = $m[2];
Try this:
image\((\d+), '(.+?)'\)
The . matches anything and the rest is pretty much self-explanatory. Group 1 is your number, group 2 is the string.
You can try this one:
image\(\s*\d+\s*\,\s*'.*'\s*\)
I have a server application which looks up where the stress is in Russian words. The end user writes a word жажда. The server downloads a page from another server which contains the stresses indicated with apostrophes for each case/declension like this жа'жда. I need to find that word in the downloaded page.
In Russian the stress is always written after a vowel. I've been using so far a regex that is a grouping of all possible combinations (жа'жда|жажда'). Is there a more elegant solution using just a regex pattern instead of making a PHP script which creates all these combinations?
EDIT:
I have a word жажда
The downloaded page contains the string жа'жда. (notice the
apostrophe, I do not before-hand know where the apostrophe in the
word is)
I want to match the word with apostrophe (жа'жда).
P.S.: So far I have a PHP script creating the string (жа'жда|жажда') used in regex (apostrophe is only after vowels) which matches it. My goal is to get rid of this script and use just regex in case it's possible.
If I understand your question,
have these options (d'isorder|di'sorder|dis'order|diso'rder|disor'der|disord'er|disorde'r|disorder') and one of these is in the downloaded page and I need to find out which one it is
this may suit your needs:
<pre>
<?php
$s = "d'isorder|di'sorder|dis'order|diso'rder|disor'der|disord'er|disorde'r|disorder'|disorde'";
$s = explode("|",$s);
print_r($s);
$matches = preg_grep("#[aeiou]'#", $s);
print_r($matches);
running example: https://eval.in/207282
Uhm... Is this ok with you?
<?php
function find_stresses($word, $haystack) {
$pattern = preg_replace('/[aeiou]/', '\0\'?', $word);
$pattern = "/\b$pattern\b/";
// word = 'disorder', pattern = "diso'?rde'?r"
preg_match_all($pattern, $haystack, $matches);
return $matches[0];
}
$hay = "something diso'rder somethingelse";
find_stresses('disorder', $hay);
// => array(diso'rder)
You didn't specify if there can be more than one match, but if not, you could use preg_match instead of preg_match_all (faster). For example, in Italian language we have àncora and ancòra :P
Obviously if you use preg_match, the result would be a string instead of an array.
Based, on your code, and the requirements that no function is called and disorder is excluded. I think this is what you want. I have added a test vector.
<pre>
<?php
// test code
$downloadedPage = "
there is some disorde'r
there is some disord'er in the example
there is some di'sorder in the example
there also' is some order in the example
there is some disorder in the example
there is some dso'rder in the example
";
$word = 'disorder';
preg_match_all("#".preg_replace("#[aeiou]#", "$0'?", $word)."#iu"
, $downloadedPage
, $result
);
print_r($result);
$result = preg_grep("#'#"
, $result[0]
);
print_r($result);
// the code you need
$word = 'also';
preg_match("#".preg_replace("#[aeiou]#", "$0'?", $word)."#iu"
, $downloadedPage
, $result
);
print_r($result);
$result = preg_grep("#'#"
, $result
);
print_r($result);
Working demo: https://eval.in/207312
I have the following in a variable, |MyString|
I want to strip the leading | and the ending | returning MyString
What is the quickest and non intensive way of doing this?
Easiest way is probably
$result = trim($input, '|');
http://docs.php.net/trim
e.g.
<?php
$in = '|MyString|';
$result = trim($in, '|');
echo $result;
prints MyString
Checkout the str_replace function in PHP http://php.net/manual/en/function.str-replace.php
this should remove all '|' characters:
str_replace('|','',$myString)
You may be able to use a regular expression to only remove the first and last '|' or alternatively using the String trim() function may also work:
http://www.php.net/manual/en/function.trim.php
So, something like this:
$trimmedMyString = trim($myString, "|");
Worth trying anyway.
When I've a string:
$string = 'word1="abc.3" word2="xyz.3"';
How can I replace the point with a comma after xyz in xyz.3 and keep him after abc in abc.3?
You've provided an example but not a description of when the content should be modified and when it should be kept the same. The solution might be simply:
str_replace("xyz.", "xyz", $input);
But if you explicitly want a more explicit match, say requiring a digit after the ful stop, then:
preg_replace("/xyz\.([0-9])+/", 'xyz\${1}', $input);
(not tested)
something like (sorry i did this with javascript and didn't see the PHP tag).
var stringWithPoint = 'word1="abc.3" word2="xyz.3"';
var nopoint = stringWithPoint.replace('xyz.3', 'xyz3');
in php
$str = 'word1="abc.3" word2="xyz.3"';
echo str_replace('xyz.3', 'xyz3', $str);
You can use PHP's string functions to remove the point (.).
str_replace(".", "", $word2);
It depends what are the criteria for replace or not.
You could split string into parts (use explode or preg_split), then replace dot in some parts (eg. str_replace), next join them together (implode).
how about:
$string = 'word1="abc.3" word2="xyz.3"';
echo preg_replace('/\.([^.]+)$/', ',$1', $string);
output:
word1="abc.3" word2="xyz,3"
If I have a description like:
"We prefer questions that can be answered, not just discussed. Provide details. Write clearly and simply."
And all I want is:
"We prefer questions that can be answered, not just discussed."
I figure I would search for a regular expression, like "[.!\?]", determine the strpos and then do a substr from the main string, but I imagine it's a common thing to do, so hoping someone has a snippet lying around.
A slightly more costly expression, however will be more adaptable if you wish to select multiple types of punctuation as sentence terminators.
$sentence = preg_replace('/([^?!.]*.).*/', '\\1', $string);
Find termination characters followed by a space
$sentence = preg_replace('/(.*?[?!.](?=\s|$)).*/', '\\1', $string);
<?php
$text = "We prefer questions that can be answered, not just discussed. Provide details. Write clearly and simply.";
$array = explode('.',$text);
$text = $array[0];
?>
My previous regex seemed to work in the tester but not in actual PHP. I have edited this answer to provide full, working PHP code, and an improved regex.
$string = 'A simple test!';
var_dump(get_first_sentence($string));
$string = 'A simple test without a character to end the sentence';
var_dump(get_first_sentence($string));
$string = '... But what about me?';
var_dump(get_first_sentence($string));
$string = 'We at StackOverflow.com prefer prices below US$ 7.50. Really, we do.';
var_dump(get_first_sentence($string));
$string = 'This will probably break after this pause .... or won\'t it?';
var_dump(get_first_sentence($string));
function get_first_sentence($string) {
$array = preg_split('/(^.*\w+.*[\.\?!][\s])/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
// You might want to count() but I chose not to, just add
return trim($array[0] . $array[1]);
}
Try this:
$content = "My name is Younas. I live on the pakistan. My email is **fromyounas#gmail.com** and skype name is "**fromyounas**". I loved to work in **IOS development** and website development . ";
$dot = ".";
//find first dot position
$position = stripos ($content, $dot);
//if there's a dot in our soruce text do
if($position) {
//prepare offset
$offset = $position + 1;
//find second dot using offset
$position2 = stripos ($content, $dot, $offset);
$result = substr($content, 0, $position2);
//add a dot
echo $result . '.';
}
Output is:
My name is Younas. I live on the pakistan.
current(explode(".",$input));
I'd probably use any of the multitudes of substring/string-split functions in PHP (some mentioned here already).
But also look for ". " OR ".\n" (and possibly ".\n\r") instead of just ".". Just in case for whatever reason, the sentence contains a period that isn't followed by a space. I think it will harden the likelihood of you getting genuine results.
Example, searching for just "." on:
"I like stackoverflow.com."
Will get you:
"I like stackoverflow."
When really, I'm sure you'd prefer:
"I like stackoverflow.com."
And once you have that basic search, you'll probably come across one or two occasions where it may miss something. Tune as you run with it!
Try this:
reset(explode('.', $s, 2));