preg_match for information in parentheses - php

(ACCTG) Accounting
The text above I trying to get the information in the parentheses how would I do that in php this is what I have so far.
$regex = '#\((([^()]+|(?R))*)\)#';
if (preg_match_all($regex, $string ,$matches)) {
echo implode(' ', $matches[1]);
} else {
//no parenthesis
echo $string;
}

I do converting special characters to hex for easy use in my regex's
<?
$input = 'abc ("an example")';
if(preg_match("/\x28([^\x29]+)\x29/", $input, $matched)) {
//...
print_r($matched);
} else {
//do something..
}
?>

Wouldn't this be sufficient:
\(([^\)]*)\).*

Related

Matching string in 2 different patterns in PHP. The code must return TRUE

Objective: strings with ' should match the string without it.
Example:
$first_string = "alex ern o'brian";
$second_string = "alex-ern o brian";
$pattern = array("/(-|\.| )/", "/(')/");
$replace = array(' ', '(\s|)');
$first_string = preg_replace($pattern, $replace, $first_string);
$second_string = preg_replace($pattern, $replace, $second_string);
$first_string_split = preg_split("/(-|\.| )/", $first_string);
$first_string_split[] = $first_string;
$second_string_split = preg_split("/(-|\.| )/", $second_string);
$second_string_split[] = $second_string;
$first_string = array_slice($first_string_split, -1)[0];
$second_string = array_slice($second_string_split, -1)[0];
if(in_array($first_string, $second_string_split) || in_array($second_string, $first_string_split))
{
echo 'true';
} else {
echo 'false';
}
I think you are expecting this.
Solution 1: Try this code snippet here
Regex: (\s|) this will match either space or null.
<?php
ini_set('display_errors', 1);
$string = "o'brian";
$string=str_replace("'", "(\s|)",$string);
$list = array("o'neal", "o brian", "obrian");
$result=array();
foreach($list as $value)
{
if(preg_match("/$string/", $value))
{
$result[]=$value;
}
}
print_r($result);
Solution 2:
Regex: [a-z]+ will match character from a to z.
$string1="o brian";
$string2="obrian";
if(preg_match("/".implode(" ", $matches[0])."/", $string1))
{
echo "matched";
}
if( preg_match("/".implode("", $matches[0])."/", $string2))
{
echo "matched";
}
I'm not sure if I got your question right, but this should do it:
(?<=\w)'(?=\w)
It matches every ' character, which is followed and preceded by a word character. The word character \w is equal to [a-zA-Z0-9_].
Here is a live example to test the regex
Here is a live PHP example

PHP preg_replace multiple words

I have a problem when replacing strings with preg_replace.
function addClass($search, $string) {
return preg_replace("/\b($search)\b/", "<div class=mark>$1</div>", $string);
}
$string = "We won again";
$result = addClass("We", $string);
output ---> <div class=mark>We</div> won again
I want to make $search for multiple strings.
$string = "We won again";
$result = addClass(array("We", "again"), $string);
output ---> <div class=mark>We</div> won <div class=mark>again</div>
How can I create multiple searches, to put strings in an array?
Thanks in advance.
You can use or expresion in regex - (We|again)
function addClass($search, $string) {
return preg_replace("/\b(". implode('|', $search) . ")\b/", "<div class=mark>$1</div>", $string);
}
And, if you want to save the old syntax, make an array from a single string:
function addClass($search, $string) {
if(! is_array($search)) $search = array($search);
return preg_replace("/\b(". implode('|', $search) . ")\b/", "<div class=mark>$1</div>", $string);
}
demo
The alternative solution using is_array and array_map functions:
function addClass($search, $string) {
$search = (is_array($search))? array_map(function($v) { return "/\b($v)\b/"; }, $search) : ["/\b($search)\b/"];
return preg_replace($search, "<div class=mark>$1</div>", $string);
}

Remove the first paragraph tags from string

String
"<p>This is </p><p>Stackoverflow</p><p>site for programmers</p>"
Required Output
"This is <p>Stackoverflow</p><p>site for programmers</p>"
Small function
function remove_p($string)
{
$first_p=substr($string,0,3);
$p="<p>";
if($first_p==$p)
{
$string=str_replace('<p>','',$string,$temp=1);
$string=str_replace('</p>','',$string,$temp=1);
}
return $string;
}
But it removes all the <p> </p> tags.Why so?
I am basically writing this to remove the first paragraph tags created by ckeditor.
str_replace acts on all occurrences of a substring, not just the first. You will want to use a different function.
$string = preg_replace('~<p>(.*?)</p>~is', '$1', $string, /* limit */ 1);
To only remove the first <p> and </p> if at the start of the string, add a ^ after the first /.
See also: Using str_replace so that it only acts on the first match?
function replaceFirst($input, $search, $replacement){
$pos = stripos($input, $search);
if($pos === false){
return $input;
}
else{
$result = substr_replace($input, $replacement, $pos, strlen($search));
return $result;
}
}
$string = "This is <p>Stackoverflow</p><p>site for programmers</p>";
echo $string;
echo replaceFirst($string, '<p>', '');
Output:
This is <p>Stackoverflow</p><p>site for programmers</p>
This is Stackoverflow</p><p>site for programmers</p>
Source: #2031045
Hope this helps!
$str = "This is <p>Stackoverflow</p><p>site for programmers</p>";
function remove_p($string)
{
$string=str_replace('<p>','',$string,$temp=1);
$string=str_replace('<\p>','',$string,$temp=1);
return $string;
}
echo(remove_p($str));
The result is:
This is Stackoverflow
site for programmers
Try using the method of this answer.
function remove_p($string)
{
return replaceFirst(replaceFirst($string, '<p>', ''), '</p>', '');
}
Or read about Regular Expressions.

Search a word in a string using php function

When i search for "bank", it should display Bank-List1, Bank-List2 from the following list.
Railway-List, Bank-List1, Bank-List2, Education, Ecommerce, Articles, Railway-List1.
Is there is any php function to display?
I got the output for exact match. But no result for this type of search.
Please help me to find the solution.
you can use stristr
stristr — Case-insensitive strstr()
<?php // Example from PHP.net
$string = 'Hello World!';
if(stristr($string, 'earth') === FALSE) {
echo '"earth" not found in string';
}
// outputs: "earth" not found in string
?>
So for your situation, if your list was in an array named $values
you could do
foreach($values as $value)
{
if(stristr($value, 'bank') !== FALSE)
{
echo $value."<br>";
}
}
You can do it using stristr. This function returns all of haystack starting from and including the first occurrence of needle to the end. Returns the matched sub-string. If needle is not found, returns FALSE.
Here is the complete code:
<?php
$str="Railway-List, Bank-List1, Bank-List2, Education, Ecommerce, Articles, Railway-List1";
$findme="bank";
$tokens= explode(",", $str);
for($i=0;$i<count($tokens);$i++)
{
$trimmed =trim($tokens[$i]);
$pos = stristr($trimmed, $findme);
if ($pos === false) {}
else
{
echo $trimmed.",";
}
}
?>
DEMO
This solution is only valid for this pattern of text is like: word1, word2, word3
<?php
$text = 'Railway-List, Bank-List1, Bank-List2, Education, Ecommerce, Articles, Railway-List1.';
function search_in_text($word, $text){
$parts = explode(", ", $text);
$result = array();
$word = strtolower($word);
foreach($parts as $v){
if(strpos(strtolower($v), $word) !== false){
$result[] = $v;
}
}
if(!empty($result)){
return implode(", ", $result);
}else{
return "not found";
}
}
echo search_in_text("bank", $text);
echo search_in_text("none", $text);
?>
output:
Bank-List1, Bank-List2
not found

PHP preg_match? How to return not matched characters?

Lets say i have:
$string = 'qwe1ASD#';
if(preg_match('/^[a-zA-Z]+$/', $string))
{
echo 'OK';
}
else
{
echo 'BAD';
}
Now, is there simple solution, to find all characters from $string which don't match expression? So in return, in place of "BAD" i want to have ex. "BAD. You can't use following characters: 1#"
Thanks in advance for any simple hints! :)
Thank you Floern, your answer suit best my needs. It have only one "preg" so it's also good for performance. Thank you again.
I implemented it for now as follw:
if(preg_match_all('/[^a-zA-Z0-9]/s', $string, $forbidden))
{
$forbidden = implode('', array_unique($forbidden[0]));
echo 'BAD. Your string contains forbidden characters: '.htmlentities($forbidden).'';
}
$tmpstring=preg_replace('~[A-Za-z]~','',$string);
if(strlen($tmpstring))
//bad chars: $tmpstring
You could use preg_match_all():
if(preg_match_all('/[^a-zA-Z]/s', $string, $matches)){
var_dump($matches); // BAD
}
else{
echo 'OK';
}
$string = 'qwe1ASD#';
if(preg_match('/^[a-zA-Z]+$/', $string))
{
echo 'OK';
}
else
{
echo 'BAD. You cannot use the following characters: ' + preg_replace('/[a-zA-Z]/', '', $string);
}
There are different ways. I find this one nice:
$check = preg_prelace('/[a-zA-Z]/', '', $string);
if ($check) echo 'BAD ' . $check;
UPDATE:
if (strlen($check)) echo 'BAD ' . $check;

Categories