function isLastNameEqual($someLastName, $otherLastName) {
// Пара "ий/ая"
if (
(mb_substr($someLastName, -2, 2) === "ий" && mb_substr($otherLastName, -2, 2) === "ая") ||
(mb_substr($someLastName, -2, 2) === "ая" && mb_substr($otherLastName, -2, 2) === "ий")
) {
return (mb_substr($someLastName, 0, -2) === mb_substr($otherLastName, 0, -2));
}
// Последня буква "а"
if (mb_substr($someLastName, -1, 1) !== "а" && mb_substr($otherLastName, -1, 1) === "а") {
return ($someLastName === mb_substr($otherLastName, 0, -1));
}
if (mb_substr($someLastName, -1, 1) === "а" && mb_substr($otherLastName, -1, 1) !== "а") {
return (mb_substr($someLastName, 0, -1) === $otherLastName);
}
return ($someLastName === $otherLastName);
}
// Проверка
var_dump(isLastNameEqual("Петров", "Петрова")); // true
var_dump(isLastNameEqual("Слуцкий", "Слуцкая")); // true
var_dump(isLastNameEqual("Сидорчук", "Сидорчук")); // true
var_dump(isLastNameEqual("Нколаев", "Грызлов")); // false
Можно ли как то их сравнить посимвольно и при совпадении Начальных 5-7 символов к примеру, пару такую не делать?
$row = json_encode(array_pop($stmt->fetchAll(PDO::FETCH_OBJ)));
/* or */
$row = json_encode($stmt->fetch());
function splitByFirstLetter(array $arr, $key="name")
{
$splitted = [];
foreach ($arr as $element) {
$firstLetter = mb_substr($element[$key], 0, 1);
$splitted[$firstLetter][] = $element;
}
return $splitted;
}
$data = [
['id' => '1', 'name' => 'яблоко'],
['id' => '2', 'name' => 'банан'],
['id' => '3', 'name' => 'баклажан'],
['id' => '4', 'name' => 'арбуз'],
['id' => '5', 'name' => 'апельсин'],
];
$data = splitByFirstLetter($data);
ksort($data); // сортировка свежеполученного массива по алфавиту.
/*
Output:
array(3) {
["а"]=>
array(2) {
[0]=>
array(2) {
["id"]=>
string(1) "4"
["name"]=>
string(10) "арбуз"
}
[1]=>
array(2) {
["id"]=>
string(1) "5"
["name"]=>
string(16) "апельсин"
}
}
["б"]=>
array(2) {
[0]=>
array(2) {
["id"]=>
string(1) "2"
["name"]=>
string(10) "банан"
}
[1]=>
array(2) {
["id"]=>
string(1) "3"
["name"]=>
string(16) "баклажан"
}
}
["я"]=>
array(1) {
[0]=>
array(2) {
["id"]=>
string(1) "1"
["name"]=>
string(12) "яблоко"
}
}
}
*/
POST - An HTTP POST to a URL of your choosing with transaction details (in either an XML or CSV format)
GET - An HTTP GET to a URL of your choosing with transaction detail you define in the query string.
SELECT `COLUMN_TYPE`
FROM `information_schema`.`COLUMNS`
WHERE 1
AND `TABLE_SCHEMA`='schema.name' -- не знаю вашей, не забудьте поменять
AND `TABLE_NAME`='orders'
AND `COLUMN_NAME`='order_id'
SELECT
`orders`.`order_id`,
`information_column_order_id`.`COLUMN_TYPE` AS 'order_id_column_type'
FROM
`orders`
JOIN `information_schema`.`COLUMNS` AS `information_column_order_id` ON (
`TABLE_SCHEMA`='schema.name' -- не знаю вашей, не забудьте поменять
AND `TABLE_NAME`='orders'
AND `COLUMN_NAME`='order_id'
)
SELECT *
FROM `table`
WHERE `status`='maubert'
AND (
(`AssosUser`='LAROQUE' AND `telepro`='DENIS') OR
(`AssosUser` IN ('LAROQUE', 'N.C.') AND `telepro` IN ('MANGEL', 'MORANGE')
);
$str = "http://site.com/catalog/visa/bla";
if (preg_match("/http:\/\/site.com\/catalog\/visa\/([A-Z0-9]*)/", $str)) {
echo "Matched";
}
class Session
{
private $Database;
public function __construct(DatabaseInterface $Database)
{
$this->Database = $Database;
}
}
interface DatabaseInterface {}
class Database implements DatabaseInterface {}
$row = $result->fetch_row();
$firstField = $row[0];
_stripSlashesRecursive($firstField);
function splitByCols($array, $columnsQuantity=3) {
$splitted = [];
$rows = floor(count($array)/$columnsQuantity);
$offset = 0;
$modulo = count($array)%$columnsQuantity;
// Разделение по строкам
for ($i=0; $i<$columnsQuantity; $i++) {
$length = ($i<$modulo ? $rows+1 : $rows);
$columns[] = array_slice($array, $offset, $length);
$offset += $length;
}
// Поворот на 90 градусов
foreach ($columns as $columnIndex=>$rows) {
foreach ($rows as $rowIndex=>$field) {
$splitted[$rowIndex][$columnIndex] = $field;
}
}
return $splitted;
}
// Проверка
$input = range(1,14);
$splitted = splitByCols($input);
foreach ($splitted as $row) {
echo implode(" ", $row);
echo PHP_EOL;
}
/*
Output:
1 6 11
2 7 12
3 8 13
4 9 14
5 10
*/
private $orders_filename = "orders.serialized";
public function getOrders()
{
// Создание массива по умолчанию
$orders = [];
// Попытка считывания данных их файла
if (file_exists($this->orders_filename)) {
// Чтение файла и запись его содержимого в переменную
$file = file_get_contents($this->orders_filename);
// Десериализация строки в массив
$orders = unserialize($file);
}
return $orders;
}
public function addOrder($order)
{
// Получения списка заказов
$orders = $this->getOrders();
// Добавление нового заказа
$orders[] = $order;
// Сериализация массива (превращение его в строку):
$serialized_orders = serialize($orders);
// Сохранение файла
$result = file_put_contents($this->orders_filename , $serialized_orders, FILE_APPEND | LOCK_EX);
return $result;
}
public function order()
{
$order = [
'1' => 'банан',
'2' => 'помидор',
];
$this->addOrder($order);
}
function login($name, $password)
{
global $gb;
$mysqli= $db->connect();
}
class user {
private $db;
public function __construct(DataBase $db)
{
$this->db = $db;
}
public function login($name, $password)
{
$mysqli = $this->db->connect();
}
}
// Инициализация класса будет выглядеть так:
$user = new user($db);
$user->login();
$context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'protocol_version' => '1.1',
'header' => array(
'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0',
)
)
));
$r = file_get_contents($url, false, $context);
var_dump($r);
На момент запуска нового сайта доступны следующие RSS:
/rss/news — новости
/rss/top7 — самые свежие и самые важные новости
/rss/last24 — главные новости за последние сутки
/rss/articles — все статьи
/rss/columns — колонки
/rss/news/russia — новости рубрики «Россия»; после косой черты можно написать английское название любой рубрики — обращайте внимание на их url (например, /rss/news/world — это уже все новости рубрики «Мир»)
/rss/articles/russia — все статьи рубрики «Россия»; управление рубриками аналогичное
/rss/photo — все галереи
/rss/photo/russia — все галереи рубрики «Россия»; управление рубриками аналогичное
libxml_use_internal_errors(true); // Не провоцировать генерацию ошибок в php из-за ошибок разбора html
$html = file_get_contents("https://lenta.ru/news/2016/06/02/trol/");
$page = new domDocument();
$page->loadHTML("<?xml version='1.0' encoding='UTF-8'?>" . $html); // Явное указание кодировки полученных данных
$article = "";
$domXpath = new DOMXPath($page);
$newDom = new DOMDocument();
$newDom->formatOutput = true;
$filtered = $domXpath->query("//div[@itemprop='articleBody']");
$i = 0;
while ($item = $filtered->item($i++)) {
$node = $newDom->importNode($item, true);
$newDom->appendChild($node);
}
$article = $newDom->saveHTML();
libxml_clear_errors(); // Очищение буфера ошибок.